SlideShare a Scribd company logo
1 of 65
Download to read offline
GIST 정보통신공학과 Winter school
프로그래밍 활용 교육:
MATLAB 1일차
강 재 욱
jwkkang@gist.ac.kr
School	of	Information	and	Communications
Feb.	2015
1
© 2015
Jaewook	Kang
All	Rights	Reserved
GIST	정보통신공학과
Winter	School	2015,	강재욱
강 사 소 개
§ GIST	정보통신공학과 박사과정
§ 센서통신 연구실 (김기선 교수)
§ Student	Chair	in	IEEE	student	branch (since	2014	Apr.)
§ 연구분야:	
§ Belief	propagation	기반의 compressive	sensing	복구 알고리즘
§ 역 선형 변환을 위한 Approximate	message-passing	알고리즘
§ 기계학습 기반의 무선통신 수신기 설계
2
§ 대표논문:
Jaewook	Kang,	Heung-No	Lee,	Kiseon Kim,	"Bayesian	Hypothesis	Test	using	
Nonparametric	Belief	Propagation	for	Noisy	Sparse	Recovery,"	 IEEE	Trans.	on	Signal	
process.,	vol.	63,	no.	4,	 pp. 935-948,	Feb.	2015
§ Contact	point:
Lab.	phone: +82-62-715-2264
E-mail	:	 jwkkang@gist.ac.kr	
Hompage:	https://sites.google.com/site/jwkang10/
Jaewook	Kang	(강재욱)
GIST	정보통신공학과
Winter	School	2015,	강재욱
강의 일정
3
일 정 시간 내 용 강 사
Day 1 (2/11)
Lab. 1 3
- MATLAB 프로그래밍 일반
- Vectorized 코딩 1
강재욱
Lab. 2 3
- 국내외 산업분야 활용 사례 소개
- 수치해석에서 테크니컬 컴퓨팅까지
- 공학기초를 위한 MATLAB과 Symbolic Math
활용법
Mathwork
초빙강사
Day 2 (2/12)
Lab. 3 3
- Vectorized 코딩 2
- 고급 MATLAB 함수 활용
강재욱
Lab. 4 3 - DATA Acquisition with Labview 송하준
Day 3 (2/13)
Lab. 5 3 - MATLAB을 이용한 통신시스템 모델링 1
장재혁
Lab. 6 3 - MATLAB을 이용한 통신시스템 모델링 2
GIST	정보통신공학과
Winter	School	2015,	강재욱
목 차
일 정 내 용
1일차 (3시간)
1. MATLAB Programs General
1. MATLAB Program Organization
2. User-defined function
3. Variable scope
4. Debugging Techniques
2. Vectorized Code
1. Loops with Vectors and Matrices
2. Operations on Vectors and Matrices
3. Vectors and Matrices as Function Arguments
2일차 (3시간)
1. Vectorized Code
4. Logical Vectors
5. Vectorizing Code
2. Advanced MATLAB Functions
1. Anonymous Functions
2. Uses of Function Handles
3. Variable Number of Arguments
4
GIST	정보통신공학과
Winter	School	2015,	강재욱
vReference	
5
MATLABW
A	Practical	Introduction
to	Programming	and
Problem	Solving
Second	Edition,	2012	Elsevier
Stormy	Attaway
Department	of	Mechanical	
Engineering
Boston	University
GIST	정보통신공학과
Winter	School	2015,	강재욱
Why MATLAB ?
v MATLAB 장점
§ “수식 to	프로그램” 이식이 간편함
§ Vectorized 코딩:	빠르고 간단한 벡터/행렬 기반 프로그래밍
§ 다양한 MATLAB	함수:	통계,	확률,	신호처리
§ 강력한 함수/데이터의 도시화 기능
6
MATLAB Mathmetica
- MathWork (1984)
- 공학시뮬레이션
- 수치적 계산& 시뮬레이션
- 계산효율성 좋음
-Wolfram	(1988)
- 공학시스템의 수학적 모델링
- 심볼릭 연산!: 수학기호를 그
대로 연산
- 계산효율성 보통
1. MATLAB Programs General
1. MATLAB Program Organization
2. User-defined function
3. Variable scope
4. Debugging Techniques
7
GIST	정보통신공학과
Winter	School	2015,	강재욱
MATLAB Program Organization
v MATLAB	파일 (m-file)의 종류
– Script	파일:	
• MATLAB	statement의 모음이 저장된 m-file
• 해당 M-file을 실행하면 그안에 있는 모든 statement가 실행됨
– User-define	Function	파일:	
• 사용자가 정의한 작업을 수행하고 특정값을 리턴하는 함수가 저장된
m-file
• 해당 함수는 MATLAB	커맨드 윈도우나 다른 script	파일에서 호출하여
사용이 가능함
8
함수 파일 스크립트 파일
GIST	정보통신공학과
Winter	School	2015,	강재욱
MATLAB Program Organization
v MATLAB	프로그램의 구성
– MATLAB	프로그램은 다양한 “MATLAB	함수 파일”과, 그 함수들을 호출하는
“Script	파일”로 구성된다.	
v Modular 프로그래밍
– 전체작업을 여러 개의 작은 모듈로 나누고, 각 모듈을 함수로 구현하여
프로그램을 구현하는 방식 (cf.	divide	and	conquer)
– 여기서 Script함수가 main	program이 된다.	(cf.	C언어 main	함수)
9
%	This	m-file	is	a	script	file	for	the	Main	Program
func_for_task1(); %	function	cal l	for	the	task	1
func_for_task2();	%	function	cal l	for	the	task	2
…
Func_for_taskN();	%	function	cal l	for	the	task	N
GIST	정보통신공학과
Winter	School	2015,	강재욱
User-define Functions
v 정의:	사용자 정의 한 작업을 수행하는 함수
– 임의의 script파일이나 command	window에서 호출가능
v ex1: function_name.m
10
%	Function	Header
function [output_arguments]=	function_name(input_arguments)
%	body	of	the	function	
end
§ 모든작업 statement를 포함
§ 모든 출력인자에 값을 할당해야함
§ 함수이름은
저장하는 M-
file이름과
동일하게
§ 여러 개의 입력인자의
구분은 컴마“,”	사용
GIST	정보통신공학과
Winter	School	2015,	강재욱
User-define Functions
v Practice1: 넓이 &	원주 계산 함수 (areacirc.m)
11
%	Function	Header
function [area,	circum]	=	areacirc(rad)
%	body	of	the	function	
end
GIST	정보통신공학과
Winter	School	2015,	강재욱
User-define Functions
v Practice1: 넓이 &	원주 계산 함수 (areacirc.m)
12
%	Function	Header
function [area,	circum]	=	areacirc(rad)
%	areacirc returns	the	area	and
%	the	circumference	of	a	circle
%	Format:	areacirc(radius)
area	=	pi	*	rad	*	rad;
circum =	2	*	pi	*	rad;
end
§ “help”를 통해서
나오는 함수에 대한
설명 주석
§ 두개의 출력인자에
값 할당
GIST	정보통신공학과
Winter	School	2015,	강재욱
User-define Functions
v ex2: 입력인자(input	arguments)가 없는 함수 (stringprompt.m)
v ex3: 출력인자(output	arguments)가 없는 함수 (printem.m)
13
function outstr =	stringprompt()
%	Also,	“function	outstr=stringprompt()”	is	fine.
%	문자열을 입력 받고 그 값을 리턴하는 함수
disp('When	prompted,	enter	a	string	of	any	length.');
outstr =	input('Enter	the	string	here:	',	's');
end
§ “()”	괄호 안을 비워둠
또는 괄호 제거 가능
function printem(a,b)
%	두 입력 인자 값을 출력하는 함수
disp(sprintf('The	first	number	is	%.1f	and	the	second	is	%.1fn',a,b));
end
§ 출력인자가 없음
§ 출력인자 값 할당
GIST	정보통신공학과
Winter	School	2015,	강재욱
User-define Functions
v Practice2: 넓이 &	원주 계산 프로그램 (calcareacirc.m)
– Modular	 프로그램밍 방식을 이용하여 다음 작업을 수행하는
프로그램을 작성하시오
• Task	1:		반지름값 입력 받기 (input	함수 이용)
• Task	2:	넓이 &	원주 계산하기 (practice	1	참조)
• Task	3:	계산한 값 도시 하기 (disp()	함수 이용)
14
GIST	정보통신공학과
Winter	School	2015,	강재욱
User-define Functions
v Practice2: 넓이 &	원주 계산 프로그램 (calcareacirc.m)
– Modular	 프로그램밍 방식을 이용하여 다음 작업을 수행하는
프로그램을 작성하시오
• Task	1:		반지름값 입력 받기 (input	함수 이용)
• Task	2:	넓이 &	원주 계산하기 (practice	1	참조)
• Task	3:	계산한 값 도시 하기 (disp()	함수 이용)
%	This	script	prompts	the	user	for	the	radius	of	a	circle,
%	calls	a	function	to	calculate	and	return	both	the	area
%	and	the	circumference,	and	prints	the	results
%	It	ignores	units	and	error-checking	for	simplicity
radius	=input('Please	enter	the	radius	of	the	circle:	');
[area	circ]	=	areacirc(radius);
disp(sprintf('For	a	circle	with	a	radius	of	%.1f,n',	radius));
disp(sprintf('the	area	is	%.1f	and	the	circumference	is	%.1fn',area,	circ));
15
GIST	정보통신공학과
Winter	School	2015,	강재욱 16
Variable Scope
v Local	variable	(지역변수)
– 호출된 함수 안에서 정의된 변수
– 해당 함수가 호출 됐을 때에 제한되어 접근 가능
– MATLAB	workspace에서 보이지 않음
v Global	variable	(전역변수)
– Workspace	뿐만 아니라 호출된 함수 안에서도 접근 가능한 변수
– -global	키워드로 사전 선언 필요함 하고 함수 안에서 사용시 global	선언이 필요함
v ex4: mysum.m +	who	(workspace변수를 도시하는 함수)
16
function	runsum =	mysum(vec)
%	mysum returns	the	sum	of	a	vector
runsum =	0;
for	i=1:length(vec)
runsum =	runsum +	vec(i);
end
end
>>	clear	
>>	who
>>	disp(mysum([5	4	1]));
10
>>	who
§ Worksparce에 변수
없음
§ 함수 실행 이후에도
Worksparce에 변수
없음
GIST	정보통신공학과
Winter	School	2015,	강재욱
Variable Scope
v ex5: mysumscript.m +	who	(workspace변수를 도시하는 함수)
17
%	mysumscript.m
vec=1:5
runsum =	0;
for	i=1:length(vec)
runsum =	runsum +	vec(i);
end
disp(runsum)
>>	clear	
>>	who
>>	mysumscript
15
>>	who
Your	variables	are:
i runsum vec
§ Script	실행
§ Script	실행 후
workspace에 변수 생성
§ Script	실행 전
workspace에 변수 없음
17
GIST	정보통신공학과
Winter	School	2015,	강재욱
Variable Scope
v Persistent	variables
– persistent로 정의된 변수는,	함수종료시 값이 clear되지 않고,	다음
함수호출까지 이전 함수에서의 값을 유지한다.	
– Persistent	변수를 초기화 하기위해서는 “clear”	명령어를 사용
v ex6:	Counting	number	(func1.m,	func2.m)
function	func1
%	func1	increments	a	normal	variable	"count"
count	=	0;
count	=	count	+1;
disp(sprintf('The	value	of	count	is	%dn',count));
end
function func2
%	func2	increments	a	persistent	variable	"count"
persistent	count
if	isempty(count)
count	=0;
end
count	=	count	+	1;
disp(sprintf('The	value	of	count	is	%dn',count));
end
§ Persistent	변수 “count”
§ 일반 변수 “count”
18
GIST	정보통신공학과
Winter	School	2015,	강재욱
>>	persistex
This	is	what	happens	with	a	"normal"	variable:
The	value	of	count	is	1
The	value	of	count	is	1
This	is	what	happens	with	a	persistent	variable:
The	value	of	count	is	1
The	value	of	count	is	2
>>	func1
The	value	of	count	is	1
>>	func2
The	value	of	count	is	3
Variable Scope
v ex6:	Counting	number	(persistex.m)
%	This	script	demonstrates	persistent	variables
%	The	first	function	has	a	variable	"count"
disp(sprintf('This	is	what	happens	with	a	"normal"	variable:n'));
func1
func1
%	The	second	fn has	a	persistent	variable	"count"
disp(sprintf('nThis is	what	happens	with	a	persistent	variable:n'))
func2
func2	
§ Count	변수는 값이
누적됨
§ 함수 종료이후
count변수의 값이
유지됨
19
GIST	정보통신공학과
Winter	School	2015,	강재욱
Debugging Techniques
v프로그램 오류의 종류
– 1)	Syntax	errors:	MATLAB	language의 오류가 원인이 되어 발생
à MATLAB	compiler에서 처리됨
– 2)	Runtime	error: 프로그램이 실행되는 동안 발생하는 오류
à 프로그램이 실행 도중에 오류로 작업을 멈춤
– 3)	Logical	errors:	프로그램어의 논리적추론이 잘못되어 발생à 가장 찾기
어려움
20
>>mystr =	'how	are	you;
???	mystr =	'how	are	you;
Error:	A	MATLAB	string	constant	is	not	terminated	properly.
>>	vec = 3:5;
>>	for	i =	1:4	disp(vec(i));	end
3
4
5
???	Attempted	to	access	vec(4);	index	
out	of	bounds	because
numel(vec)=	3.
Error	in	=>	runtimeEx at	6
disp(vec(i))
GIST	정보통신공학과
Winter	School	2015,	강재욱
Debugging Techniques
vDebugging	기법 1:	Tracing	
– Loop	(“for	or	“while”)나 분기문 (“if”	or	“switch”)을 추적하는 기법
v Ex7)	변수값의 범위 판별 (testifelse.m)
21
>>	testifelse(4)
In	middle	of	range
>>	testifelse(7)
In	middle	of	range
>>	testifelse(-2)
In	middle	of	range
function testifelse(x)
%	testifelse will	test	the	debugger
if	3	<	x	<	6
disp('In	middle	of	range')
else
disp('Out	of	range')
end
end
§ A	Logical	error!
GIST	정보통신공학과
Winter	School	2015,	강재욱
Debugging Techniques
vDebugging	기법 1:	Tracing	
v Ex8)	echo	함수의 사용
– Echo()는 실행되는 statement	내용과 결과를 모두 도시한다.
22
>>	echo	testifelse on
>>	testifelse(-2)
%	This	function	will	test	the	debugger
if	3	<	x	<	6
disp('In	middle	of	range')
In	middle	of	range
end
§ If문에 문제가
있음을 알수 있음
GIST	정보통신공학과
Winter	School	2015,	강재욱
Debugging Techniques
vDebugging	기법 2:	Breakingpoint의 설정
v Ex9)	dbstop()&dbcont()	함수의 사용
– 함수 실행 도중 Breakingpoint를 만들어 중간시점에서 코드를 점검할 수
있다.
23
>>	dbstop testifelse 5
>>	testifelse(-2)
5	 disp('In	middle	of	range')
K>>	x
X	=
-2
K>>	3	<	x
ans =
0
K>>	3	<	x	<	6
ans =
1
K>>	dbcont
In	middle	of	range
end
§ testifelse 함수
5번째 라인에
breakingpoint를
설정
§ testifelse 함수
5번째 라인
§ Breakingpoint
종료
GIST	정보통신공학과
Winter	School	2015,	강재욱
Debugging Techniques
vDebugging	기법 2:	Breakingpoint의 설정
v Ex9)	dbstop()&dbcont()	함수의 사용
– 함수 실행 도중 Breakingpoint를 만들어 중간시점에서 코드를 점검할 수
있다.
24
>>	dbstop testifelse 5
>>	testifelse(-2)
5	 disp('In	middle	of	range')
K>>	x
x	=
-2
K>>	3	<	x
ans =
0
K>>	3	<	x	<	6
ans =
1
K>>	dbcont
In	middle	of	range
end
§ 오류의 이유는
if문의 조건 설정이
잘못됨
§ 3<	x	<6	은
complier가
(3	<		x	)	<	6로 이해
§ 즉 결과는
è (	3	<	-2	)	<6
è 0 <	6	
è 1
§ 결과적으로,	항상
“in	middle	of	range”
가 출력됨
2. Vectorized Code
1. Loops with Vectors and Matrices
2. Operations on Vectors and Matrices
3. Vectors and Matrices as Function Arguments
25
GIST	정보통신공학과
Winter	School	2015,	강재욱
Loops with Vectors and Matrices
v MATLAB에서는 벡터/행렬 단위의 계산이 가능함
– 모든 연산자에 대해서 성립
– 벡터/행렬의 각 항에 접근하기 위한 loop가 필요없음
v Ex10)	vectorized coding	with	scalar
26
>>	v=[3	7	2	1]
>>	for	i =	1:length(v)
v(i)	=	v(i)	*	3;
end
>>	v
v	=
9		21		6	 3
%	MATLAB에서만 가능함
>>	v=[3	7	2	1]
>>	v=v*3
v	=
9		21		6		3
Conventional	coding Vectorized coding
§ Loop가
필요없음
GIST	정보통신공학과
Winter	School	2015,	강재욱
Operations on Vectors and Matrices
v Array	operation	1	– 덧셈 (	+	)	/뺄셈(	- )
– Term	by	term	or	element	by	element	operation	
v Ex11)	array	operation:	덧셈
27
>>	v1	=	2:5
v1	=
2			3			4			5
>>	v2	=	[33	11	5	1]
v2	=
33			11			5			1
>>	v1	+	v2
ans =
35			14			9			6
>>	mata =	[5:8;	9:-2:3]
mata =
5			6			7			8
9			7			5			3
>>	matb =	reshape(1:8,2,4)
matb =
1			3			5			7
2			4			6			8
>>	mata - matb
ans =
4			3	 2			1
7			3			1			5
§ 1:8까지를
2by4	행렬로
만들어주는
함수
GIST	정보통신공학과
Winter	School	2015,	강재욱
Operations on Vectors and Matrices
v Array	operation	2	–지수셈 (.^)
– Term	by	term	or	element	by	element	operation	
v Ex12)	array	operation:	지수셈
– 요소단위로 연산을 하는 경우 연산자 앞에 반드시 ‘.’	dot이
필요하다 즉 (.^).	
28
>>	v	=	[3	7	2	1];
>>	v	^	2
???	Error	using	==>	mpower
Inputs	must	be	a	scalar	and	a	
square	matrix.
To	compute	elementwise
POWER,	use	POWER	(.^)	instead.
>>	v	.^	2
ans =
9			49			4			1
GIST	정보통신공학과
Winter	School	2015,	강재욱
Operations on Vectors and Matrices
v Array	operation	3	– 곱셈 (.*),	나눗셈 (	./	),	
– Term	by	term	or	element	by	element	operation	
v Ex13)	array	operation:	곱셈&나눗셈
- 연산자 앞에 반드시 ‘.’	dot이 필요하다 즉 (.*), (./).	
29
>>	v1	=	2:5
v1	=
2			3	 4			5
>>	v2	=	[33	11	5	1]
v2	=
33			11			5	 1
>>	v1	.*	v2
ans =
66			33			20	 5
>>	mata =	[5:8;	9:2:3]
mata =
5			6			7			8
9			7			5			3
>>	matb =	reshape(1:8,	2,4)
matb =
1			3			5			7
2			4	 6			8
>>	mata ./	matb
ans =
5.0000			2.0000			1.4000			1.1429
4.5000			1.7500			0.8333			0.3750
GIST	정보통신공학과
Winter	School	2015,	강재욱
Operations on Vectors and Matrices
vPractice	3:	array	operation
– Create	a	vector	variable	and	add	2	to	every	element	in	it.
– Create	a	matrix	variable	and	divide	every	element	by	3.
– Create	a	matrix	variable	and	square	every	element.
30
GIST	정보통신공학과
Winter	School	2015,	강재욱
Vectors and Matrices
as Function Arguments
v MATLAB에서는 벡터&행렬을 입력인자로 전달 할 수 있다.	
– 함수의 출력인자와 입력인자는 같은 사이즈의 벡터/행렬이다.
v Ex14)		MATLAB	bulit-in	함수 with	vector	input	arguments
31
>>	vec =	2:1
vec =
2			1			0			1
>>	sinvec =	sin(vec)
sinvec =
0.9093			0.8415			0	0.8415
>>	mat	=	[0	4	-3;	-1	0	2]
mat	=
0			4			3
1			0			2
>>	sign(mat)
ans =
0			1			1
1			0			1
GIST	정보통신공학과
Winter	School	2015,	강재욱
Vectors and Matrices
as Function Arguments
v Ex15)	User-define	함수 with	vector	input	arguments	(calcarea.m)
v 함수 calcarea()을 어떻게 수정해야 하는가?
32
function area	=	calcarea(rad)
%	calcarea calculates	the	area	of	a	circle
%	Returns	the	area
area	=	pi	*	rad	*	rad;
end
>>	calcarea(1:3)
???	Error	using	==>	mtimes
Inner	matrix	dimensions	must	agree.
Error	in	==>	calcarea at	6
area	¼	pi	*	rad	*	rad;
GIST	정보통신공학과
Winter	School	2015,	강재욱
Vectors and Matrices
as Function Arguments
v Ex16)	User-define	함수 with	vector	input	arguments	(calcarea.m)
v 함수 calcarea()을 어떻게 수정해야 하는가?
33
function	area	=	calcarea(rad)
%	calcarea calculates	the	area	of	a	circle
%	Returns	the	area
area	=	pi	*	rad	*	rad;
end
>>	calcarea(1:3)
???	Error	using	==>	mtimes
Inner	matrix	dimensions	must	agree.
Error	in	==>	calcarea at	6
area	¼	pi	*	rad	*	rad;
function area	=	calcareaii(rad)
%	calcarea calculates	the	area	of	a	circle
%	The	input	argement can	be	a	vector	of	radii
%	Returns	the	area
area	=	pi	*	rad.	*	rad;
%We	can	also	use		area	=	pi	*	rad.	^2;
end
GIST	정보통신공학과
Winter	School	2015,	강재욱
Warping up – Day 1
1. MATLAB Programs General
1. MATLAB Program Organization
2. User-defined function
3. Variable scope
4. Debugging Techniques
2. Vectorized Code
1. Loops with Vectors and Matrices
2. Operations on Vectors and Matrices
3. Vectors and Matrices as Function Arguments
34
GIST 정보통신공학과 Winter school
프로그래밍 활용 교육:
MATLAB 2일차
강 재 욱
jwkkang@gist.ac.kr
School	of	Information	and	Communications
Feb.	2015
35
© 2015
Jaewook	Kang
All	Rights	Reserved
GIST	정보통신공학과
Winter	School	2015,	강재욱
강의 일정
36
일 정 시간 내 용 강 사
Day 1 (2/11)
Lab. 1 3
- MATLAB 프로그래밍 일반
- Vectorized 코딩 1
강재욱
Lab. 2 3
- 국내외 산업분야 활용 사례 소개
- 수치해석에서 테크니컬 컴퓨팅까지
- 공학기초를 위한 MATLAB과 Symbolic Math
활용법
Mathwork
초빙강사
Day 2 (2/12)
Lab. 3 3
- Vectorized 코딩 2
- 고급 MATLAB 함수 활용
강재욱
Lab. 4 3 - DATA Acquisition with Labview 송하준
Day 3 (2/13)
Lab. 5 3 - MATLAB을 이용한 통신시스템 모델링 1
장재혁
Lab. 6 3 - MATLAB을 이용한 통신시스템 모델링 2
GIST	정보통신공학과
Winter	School	2015,	강재욱
목 차
일 정 내 용
1일차 (3시간)
1. MATLAB Programs General
1. MATLAB Program Organization
2. User-defined function
3. Variable scope
4. Debugging Techniques
2. Vectorized Code
1. Loops with Vectors and Matrices
2. Operations on Vectors and Matrices
3. Vectors and Matrices as Function Arguments
2일차 (3시간)
1. Vectorized Code
4. Logical Vectors
5. Vectorizing Code
2. Advanced MATLAB Functions
1. Anonymous Functions
2. Uses of Function Handles
3. Variable Number of Arguments
37
2. Vectorized Code
4. Logical Vectors
5. Vectorizing codes
38
GIST	정보통신공학과
Winter	School	2015,	강재욱
Logical Vectors
v 정의:	논리값(true	or	false)을 요소로 가지는 벡터
v Ex17)	벡터의 논리 연산
39
>>	vec=[5	9	3	4	6	11];
>>	isg =	vec <5
0			1			0			0			1			1
>>	whos
Name	 Size											Bytes															Class
isg 1x6															6															logical	array
vec	 1x6													48														double	array
>>	sum(isg)	
ans	=
3
>>	vec(isg)
ans	=
9									6						11
§ ‘1’	or	‘0’로만
표현됨
§ Low	memory	
사용
§ Sum()으로 vec<5	을
만족한 요소의 수를
구할수 있음
§ Logical	vector는
벡터변수의 index로
사용이 가능함
GIST	정보통신공학과
Winter	School	2015,	강재욱
Logical Vectors
v Ex 18)	Logical	vector변수의 선언
– Logical	()	,	false(),	true()함수를 사용하여 logical	vector를 선언할 수 있다.
40
>>	logical(zeros(2))
ans =
0				0
0				0
>>	logical(ones(1,5))
ans =
1			1			1	 1			1
>>	false(2)
ans =
0				0
0				0
>>	true(1,5)
ans =
1			1			1			1			1
§ logical	함수는
double값을 logical	
datatype으로 변환
§ false()	와 true()를
이용하면 더욱 빠른
생성이 가능함
GIST	정보통신공학과
Winter	School	2015,	강재욱
Logical Vectors
v Ex 19)	Logical	built-in	함수 (	any()	&	all()	)
– any()와 all()	함수의 사용:
– any()	함수는 입력인자 vec의 요소가 하나라도 nonzero인 경우 true를 리턴
– all()		함수는 입력인자 모두가 nonzero인 경우 true를 리턴
41
>>	vec1	=	[1	3	1	1	2];
>>	any(vec1)
ans =
1
>>	all(vec1)
ans =
1
>>	vec2	=	[1	1	0	1]
vec2	=
1	1	0	1
>>	any(vec2)
ans =
1
>>	all(vec2)
ans =
0
§ vec의 요소는 모두
nonzero인 경우
§ 적어도 하나의
nonzero를
포함함으로 any()는
‘true’를 리턴
§ 모두 nonzero가
아니므로 all()는
‘false’를 리턴
GIST	정보통신공학과
Winter	School	2015,	강재욱
Logical Vectors
v Ex 20)	Logical	built-in	함수 (	find()	)
– find()	함수의 사용:	입력 조건문을 만족시키는 요소의 인덱스와 값을 리턴
42
>>	vec	=	[5	3	6	7	2]
vec =
5			3	 6			7	 2
>>[index,	value]=	find(vec >	5)
index	=	
3			4
value	=
6			7
GIST	정보통신공학과
Winter	School	2015,	강재욱
Logical Vectors
v Practice	4:	
– vec=[	11			– 33			2			8			-4			25];
– 위의 vec에서 find()함수를 이용하여 음수의 항을 제거 하시오
43
GIST	정보통신공학과
Winter	School	2015,	강재욱
Logical Vectors
v Practice	5:	
– Task	1:	randint()와 함수를 이용하여 [1,	100]의 범위에서 100	by	1	정수 벡터
vec1를 생성
– Task	2:	vec1벡터에서 “50	보다 큰 값을 가지는 항”에 대한 index	벡터 생성
– Task	3:	index벡터를 이용하여 vec1벡터에서 “50	보다 큰 값을 가지는 항”을
추출하여 새로운 벡터 vec2를 생성
44
GIST	정보통신공학과
Winter	School	2015,	강재욱
Logical Vectors
v Ex 21)	Logical	built-in	함수 (	isequal()	)
– isequal()	함수의 사용:	두 벡터가 같은 벡터인지 확인한다.	
– isequal ()함수와 “==“연산자와의 차이
45
>>	vec1	=	[1	3	4	2	99];
>>	vec2	=	[1	2	4	3	99];
>>	vec1	==	vec2
ans =
1	0	1	0	1
>>	all(vec1	==	vec2)
ans =
0
>>	isequal(vec1,vec2)
ans =
0
§ “==“연산자는 elem by	
elem으로 비교
§ isequal()	함수는
벡터단위로 비교
GIST	정보통신공학과
Winter	School	2015,	강재욱
Vectorizing codes
v 정의:	MATLAB에서 제공 벡터/행렬 연산과 built-in	함수들을
이용하여,	효율적으로 다시 프로그래밍 한 코드
– Array	operation	:	(.*),	,(./),	(.^)
– Built-in	functions:	any()	all()	find(),	and	so	on…
– Preallocation of	vectors:	zeros(),	ones(),	and	so	on..
46
GIST	정보통신공학과
Winter	School	2015,	강재욱
Vectorizing codes
v Ex22)	행렬의 각 요소의 부호를 알아보는 함수 (	signum.m)
47
function outmat =signum(mat)
%	signum imitates	the	sign	function
[r	c]	=	size(mat);
for	i =	1:r
for	j	=	1:c
if	mat(i,j)	>	0
outmat(i,j)	=	1;
elseif mat(i,j)	==	0
outmat(i,j)	=	0;
else
outmat(i,j)	=	-1;
end
end
end
end
>>	mat	=	[0	4	-3;	-1	0	2]
mat	=
0				4				-3
-1	 0					2
>>	signum(mat)
ans =
0				1				-1
-1	 0					1
GIST	정보통신공학과
Winter	School	2015,	강재욱
Vectorizing codes
v Ex22)	행렬의 각 요소의 부호를 알아보는 함수 (	signum.m)
– 동일연산이 MATLAB	built-in	함수인 sign()을 사용하여 효율적으로 수행될 수 있음
– 대부분의 수학연산 함수,	sqrt(),exp(),log(),가 벡터/행렬 연산을 지원함
48
function outmat =signum(mat)
%	signum imitates	the	sign	function
[r	c]	=	size(mat);
for	i =	1:r
for	j	=	1:c
if	mat(i,j)	>	0
outmat(i,j)	=	1;
elseif mat(i,j)	==	0
outmat(i,j)	=	0;
else
outmat(i,j)	=	-1;
end
end
end
end
>>	mat	=	[0	4	-3;	-1	0	2]
mat	=
0				4				-3
-1	 0					2
>>	signum(mat)
ans =
0				1				-1
-1	 0					1
GIST	정보통신공학과
Winter	School	2015,	강재욱
Vectorizing codes
v Ex23)	diff(x)	함수의 사용
– 입력벡터 x에 대하여 𝑋" − 𝑋"$%   ∀𝑖 ∈ {2, . . . , 𝑁} 을 리턴
– 출력벡터은 따라서 N-1의 길이를 가진다.	
49
>>	diff([4	7	15	32])
ans =
3				8	 17
>>	diff([4	7	2	32])
ans =
3				5				30
GIST	정보통신공학과
Winter	School	2015,	강재욱
Vectorizing codes
v Ex24)	CPU	runtime	measuring	using	tic/toc (fortictoc.m)
50
>>	fortictoc
Elapsed	time	is	0.088591	seconds.
%	fortictoc.m
tic
mysum =	0;
for	i =	1:20000000
mysum =	mysum +	i;
end
toc
GIST	정보통신공학과
Winter	School	2015,	강재욱
Vectorizing codes
v Ex25)	Preallocation (tictocprealloc.m)	
51
>>	tictocprealloc
No	preallocation
Elapsed	time	is	0.070526	seconds.
Preallocation
Elapsed	time	is	0.001177	seconds..
%	tictocprealloc.m shows	the	timing	difference	between	preallocating a	vector	vs.	not
clear
disp('No	preallocation')
tic
for	i =	1:10000
x(i)	=	sqrt(i);
end
toc
disp('Preallocation')
tic
y	=zeros(1,10000);
for	i =	1:10000
y(i)	=	sqrt(i);
end
toc
§ Preallocation을
사용하지 않는 경우
§ Preallocation을
사용하는 경우
3. Advanced MATLAB Functions
1. Anonymous Functions
2. Uses of Function handles
3. Variable Number of Arguments
52
GIST	정보통신공학과
Winter	School	2015,	강재욱
Anonymous Function
v Anonymous	Function
– 따로 m-file로 저장하지 않고, 단순 연산을 one-line으로 정의하여 사용하는 함수
• Function	handle:	함수호출 시 사용하는 reference
• Arguments:	입력인자
• Function	body:	함수연산 내용
•
v Ex	26)	원 넓이 구하는 함수 (ver.	anonymous	function)
53
fnhandle=	@	(arguments)	functionbody;
cirarea=	@(rad)	pi*rad	.^2;
>>	cirarea(4)
ans =
50.2655
>>	cirarea(1:4)
ans =
3.1416	12.5664	28.2743	50.2655.
§ (.^)을 사용하여
벡터연산도 가능함
GIST	정보통신공학과
Winter	School	2015,	강재욱
Anonymous Function
v Anonymous	Function
– M-file 함수와는 달리 입력인자가 없는 경우에도 괄호 ()를 포함 해야 한다.
– 괄호 ()	를 포함하지 않는 호출의 경우 function	handle은 함수 정의를
보여준다.
v Practice	6:	Anonymous	function을 사용하여 원주를 계산하는
프로그램을 작성하시오
54
>>	prtran =@	()	disp(	sprintf('%.2fn',rand)	);
>>	prtran()
0.95
>>	prtran
Prtran =
@	()	disp(	sprintf('%.2fn',rand)	)
GIST	정보통신공학과
Winter	School	2015,	강재욱
Uses of Function handles
v Function	handle은 일반함수에 대해서도 생성될 수 있다.	
– “@”	는 일반함수로 부터 Function	handle을 얻는 연산자임
55
>>	facth =	@factorial;
>>	facth (5)
ans =	
120
§ facth는 built-in	함수
factorial()의 function	
handle임
§ function	handle을
사용한 함수호출
GIST	정보통신공학과
Winter	School	2015,	강재욱
Uses of Function handles
v Function	handle을 사용하는 이유
– Function	handle를 다른 함수의 입력인자로 전달하기 위해서임
– 입력 Function	handle에 따라서 다른 작업수행을 하는 함수를 정의가능
v Ex	27)	Function	handle을 입력인자로 받는 함수 (fnfnexamp.m)
56
function fnfnexamp(funh)
%	fnfnexamp receives	the	handle	of	a	function
%	and	plots	that	function	of	x	(which	is	1:.25:6)
x	=1:.25:6;
y	=	funh(x);
plot(x,y,'ko')
xlabel('x')
ylabel('fn(x)')
title(func2str(funh))
end
§ 입력인자 function	
handle에 따라서 다른
동작을 수행
§ 작업수행결과를 plot
§ 입력인자에
function	handle
GIST	정보통신공학과
Winter	School	2015,	강재욱
Uses of Function handles
v Function	handle을 사용하는 이유
– Function	handle를 다른 함수의 입력인자로 전달하기 위해서임
– 입력 Function	handle에 따라서 다른 작업수행을 하는 함수를 정의가능
v Ex	27)	Function	handle을 입력인자로 받는 함수 (fnfnexamp.m)
57
>>	fnfnexamp(@sin) >>	fnfnexamp(@cos)
§ 입력인자 function	
handle에 따라서 다른
동작을 수행
§ 입력인자에
function	handle
GIST	정보통신공학과
Winter	School	2015,	강재욱
Variable Number of Arguments
v Variable	number	of	input	arguments
– varargin :	입력인자를 저장하는 cell	array	
– nargin:						입력인자의 개수
v Ex 28)	원의 넓이는 계산하는 함수 (varargin.m)
– 첫째 입력인자는 반지름
– 두째 입력인자는 단위를 정한다.	
– 함수에 첫째 입력인자만 전달되는 경우 default로 ‘feet’	단위로 계산
– 두번째 입력인자가 ‘i’인 경우 ‘inche’	단위로 계산
58
GIST	정보통신공학과
Winter	School	2015,	강재욱
Variable Number of Arguments
v Ex 28)	원의 넓이는 계산하는 함수 함수 (areafori.m)
59
function area	=	areafori(varargin)
%	areafori returns	the	area	of	a	circle	in	feet
%	The	radius	is	passed,	and	potentially	the	unit	of
%	inches	is	also	passed,	in	which	case	the	result	will	be
%	given	in	inches	instead	of	feet
n	= nargin;	%	number	of	input	arguments
radius	=	varargin{1};	%	Given	in	feet	by	default
if	n	==2
unit	=	varargin{2};
%	if	inches	is	specified,	convert	the	radius
if	unit	==	'i'
radius	=	radius	*	12;
end
end
area	=	pi	*	radius	.^	2;
end
§ 입력인자가 2개고
두째인자가 ‘i'인
경우 inche로 변환
GIST	정보통신공학과
Winter	School	2015,	강재욱
Variable Number of Arguments
v Ex 28)	원의 넓이는 계산하는 함수 함수 (areafori.m)
v Practice	7:	등비수열의 합 계산 함수
1 + 𝑟 + 𝑟2 + 𝑟3 + 𝑟4 +⋅⋅⋅ +𝑟6
– 첫째인자:	r의 값
– 둘째인자:	n의 값
– 리턴:	합의 값
– 둘째 인자가 없는경우 n을 [5,30]에서 랜덤하게 발생해서 계산
60
>>	areafori(3)
ans =
28.2743
>>	areafori(1,'i')
ans =
452.3893
GIST	정보통신공학과
Winter	School	2015,	강재욱
Variable Number of Arguments
v Variable	number	of	output	arguments
– varargout :	출력인자를 저장하는 cell	array	
– nargout:						출력인자의 개수
v Ex 29)	입력의 데이터타입과 사이즈를 리턴하는 함수 (typesize.m)
– 입력인자가 스칼라인경우 ‘s’를 출력
– 입력인자가 벡터인 경우 ‘v’를 출력하고 길이를 출력
– 입력인자가 행렬인 경우 ‘m’을 출력하고 ‘행’/’열’	길이를 출력
61
GIST	정보통신공학과
Winter	School	2015,	강재욱
Variable Number of Arguments
v Ex 29)	입력의 데이터타입과 사이즈를 리턴하는 함수 (typesize.m)
62
function [arrtype,	varargout]	=	typesize(inputval)
%	typesize returns	a	character	's'	for	scalar,	'v'
%	for	vector,	or	'm'	for	matrix	input	argument
%	also	returns	length	of	a	vector	or	dimensions	of	matrix
[r	c	]	=	size(inputval);
if	r==1	&&	c==1
arrtype =	's';
elseif	r==1	||	c==1
arrtype ='v';
varargout{1}	=	length(inputval);
else
arrtype =	'm';
varargout{1}	=	r;
varargout{2}	=	c;
end
end
§ 스칼라인 경우
-‘s’만 출력
§ 벡터인 경우
- ‘v’출력
-길이 출력
§ 행렬인 경우
- ‘m’	출력
- 행 길이 출력
- 열 길이 출력
GIST	정보통신공학과
Winter	School	2015,	강재욱
Variable Number of Arguments
v Ex 29)	입력의 데이터타입과 사이즈를 리턴하는 함수 (typesize.m)
63
>>	typesize(5)
ans =
s
>>	[arrtype,	len]	=	typesize(4:6)
arrtype =
v
len =
3
>>	[arrtype,	r,	c]	=	typesize([4:6;3:5])
arrtype =
m
r	=
2
c	=
3
§ 스칼라인 경우
-‘s’만 출력
§ 벡터인 경우
- ‘v’출력
-길이 출력
§ 행렬인 경우
- ‘m’	출력
- 행 길이 출력
- 열 길이 출력
GIST	정보통신공학과
Winter	School	2015,	강재욱
Variable Number of Arguments
v Ex 30)	출력인자 개수에 따라 추가적인 정보를 제공하는 함수(mysize.m)
64
function [row	col	varargout]	=	mysize(mat)
%	mysize returns	dimensions	of	input	argument
%	and	possibly	also	total	#	of	elements
[row	col]	=	size(mat);
if	nargout ==	3
varargout{1}	=	row*col;
end
end
§ 세번째 출력인자를
요구하는 경우 “전체
elem의 개수”를 출력
>>	[r	c]	=	mysize(eye(3))
r	=
3
c	=
3
>>	[r	c	elem]	=	mysize(eye(3))
r	=
3
c	=
3
elem =
9
§ 세번째 출력인자를
요구하는 경우 “전체
elem의 개수”를 출력
§ Eye(3)=
1
1
1
GIST	정보통신공학과
Winter	School	2015,	강재욱
Warping up – Day 2
1. Vectorized Code
4. Logical Vectors
5. Vectorizing Code
2. Advanced MATLAB Functions
1. Anonymous Functions
2. Uses of Function Handles
3. Variable Number of Arguments
65

More Related Content

What's hot

기계 학습의 현재와 미래
기계 학습의 현재와 미래기계 학습의 현재와 미래
기계 학습의 현재와 미래Joon Kim
 
[Tf2017] day3 jwkang_pub
[Tf2017] day3 jwkang_pub[Tf2017] day3 jwkang_pub
[Tf2017] day3 jwkang_pubJaewook. Kang
 
순환신경망(Recurrent neural networks) 개요
순환신경망(Recurrent neural networks) 개요순환신경망(Recurrent neural networks) 개요
순환신경망(Recurrent neural networks) 개요Byoung-Hee Kim
 
[Tf2017] day2 jwkang_pub
[Tf2017] day2 jwkang_pub[Tf2017] day2 jwkang_pub
[Tf2017] day2 jwkang_pubJaewook. Kang
 
The bleeding edge of machine learning stream in 2017 - APAC ML/DS Community ...
The bleeding edge of  machine learning stream in 2017 - APAC ML/DS Community ...The bleeding edge of  machine learning stream in 2017 - APAC ML/DS Community ...
The bleeding edge of machine learning stream in 2017 - APAC ML/DS Community ...Jeongkyu Shin
 
[기초개념] Recurrent Neural Network (RNN) 소개
[기초개념] Recurrent Neural Network (RNN) 소개[기초개념] Recurrent Neural Network (RNN) 소개
[기초개념] Recurrent Neural Network (RNN) 소개Donghyeon Kim
 
Deep learning framework 제작
Deep learning framework 제작Deep learning framework 제작
Deep learning framework 제작Tae Young Lee
 
한글 언어 자원과 R: KoNLP 개선과 활용
한글 언어 자원과 R: KoNLP 개선과 활용한글 언어 자원과 R: KoNLP 개선과 활용
한글 언어 자원과 R: KoNLP 개선과 활용r-kor
 
인공지능 방법론 - 딥러닝 이해하기
인공지능 방법론 - 딥러닝 이해하기인공지능 방법론 - 딥러닝 이해하기
인공지능 방법론 - 딥러닝 이해하기Byoung-Hee Kim
 
인공지능 방법론 - Deep Learning 쉽게 이해하기
인공지능 방법론 - Deep Learning 쉽게 이해하기인공지능 방법론 - Deep Learning 쉽게 이해하기
인공지능 방법론 - Deep Learning 쉽게 이해하기Byoung-Hee Kim
 
Tensorflow for Deep Learning(SK Planet)
Tensorflow for Deep Learning(SK Planet)Tensorflow for Deep Learning(SK Planet)
Tensorflow for Deep Learning(SK Planet)Tae Young Lee
 
개인 일정관리에 Agile을 끼얹으면?
개인 일정관리에 Agile을 끼얹으면?개인 일정관리에 Agile을 끼얹으면?
개인 일정관리에 Agile을 끼얹으면?Curt Park
 
Papago/N2MT 개발이야기
Papago/N2MT 개발이야기Papago/N2MT 개발이야기
Papago/N2MT 개발이야기NAVER D2
 
[226]대용량 텍스트마이닝 기술 하정우
[226]대용량 텍스트마이닝 기술 하정우[226]대용량 텍스트마이닝 기술 하정우
[226]대용량 텍스트마이닝 기술 하정우NAVER D2
 
[224] backend 개발자의 neural machine translation 개발기 김상경
[224] backend 개발자의 neural machine translation 개발기 김상경[224] backend 개발자의 neural machine translation 개발기 김상경
[224] backend 개발자의 neural machine translation 개발기 김상경NAVER D2
 
딥러닝 논문 리뷰 Learning phrase representations using rnn encoder decoder for stati...
딥러닝 논문 리뷰 Learning phrase representations using rnn encoder decoder for stati...딥러닝 논문 리뷰 Learning phrase representations using rnn encoder decoder for stati...
딥러닝 논문 리뷰 Learning phrase representations using rnn encoder decoder for stati...keunbong kwak
 
딥러닝 자연어처리 - RNN에서 BERT까지
딥러닝 자연어처리 - RNN에서 BERT까지딥러닝 자연어처리 - RNN에서 BERT까지
딥러닝 자연어처리 - RNN에서 BERT까지deepseaswjh
 
제11회공개sw개발자대회 금상 TensorMSA(소개)
제11회공개sw개발자대회 금상 TensorMSA(소개)제11회공개sw개발자대회 금상 TensorMSA(소개)
제11회공개sw개발자대회 금상 TensorMSA(소개)Susang Kim
 
딥러닝 기반의 자연어처리 최근 연구 동향
딥러닝 기반의 자연어처리 최근 연구 동향딥러닝 기반의 자연어처리 최근 연구 동향
딥러닝 기반의 자연어처리 최근 연구 동향LGCNSairesearch
 
[한국어] Neural Architecture Search with Reinforcement Learning
[한국어] Neural Architecture Search with Reinforcement Learning[한국어] Neural Architecture Search with Reinforcement Learning
[한국어] Neural Architecture Search with Reinforcement LearningKiho Suh
 

What's hot (20)

기계 학습의 현재와 미래
기계 학습의 현재와 미래기계 학습의 현재와 미래
기계 학습의 현재와 미래
 
[Tf2017] day3 jwkang_pub
[Tf2017] day3 jwkang_pub[Tf2017] day3 jwkang_pub
[Tf2017] day3 jwkang_pub
 
순환신경망(Recurrent neural networks) 개요
순환신경망(Recurrent neural networks) 개요순환신경망(Recurrent neural networks) 개요
순환신경망(Recurrent neural networks) 개요
 
[Tf2017] day2 jwkang_pub
[Tf2017] day2 jwkang_pub[Tf2017] day2 jwkang_pub
[Tf2017] day2 jwkang_pub
 
The bleeding edge of machine learning stream in 2017 - APAC ML/DS Community ...
The bleeding edge of  machine learning stream in 2017 - APAC ML/DS Community ...The bleeding edge of  machine learning stream in 2017 - APAC ML/DS Community ...
The bleeding edge of machine learning stream in 2017 - APAC ML/DS Community ...
 
[기초개념] Recurrent Neural Network (RNN) 소개
[기초개념] Recurrent Neural Network (RNN) 소개[기초개념] Recurrent Neural Network (RNN) 소개
[기초개념] Recurrent Neural Network (RNN) 소개
 
Deep learning framework 제작
Deep learning framework 제작Deep learning framework 제작
Deep learning framework 제작
 
한글 언어 자원과 R: KoNLP 개선과 활용
한글 언어 자원과 R: KoNLP 개선과 활용한글 언어 자원과 R: KoNLP 개선과 활용
한글 언어 자원과 R: KoNLP 개선과 활용
 
인공지능 방법론 - 딥러닝 이해하기
인공지능 방법론 - 딥러닝 이해하기인공지능 방법론 - 딥러닝 이해하기
인공지능 방법론 - 딥러닝 이해하기
 
인공지능 방법론 - Deep Learning 쉽게 이해하기
인공지능 방법론 - Deep Learning 쉽게 이해하기인공지능 방법론 - Deep Learning 쉽게 이해하기
인공지능 방법론 - Deep Learning 쉽게 이해하기
 
Tensorflow for Deep Learning(SK Planet)
Tensorflow for Deep Learning(SK Planet)Tensorflow for Deep Learning(SK Planet)
Tensorflow for Deep Learning(SK Planet)
 
개인 일정관리에 Agile을 끼얹으면?
개인 일정관리에 Agile을 끼얹으면?개인 일정관리에 Agile을 끼얹으면?
개인 일정관리에 Agile을 끼얹으면?
 
Papago/N2MT 개발이야기
Papago/N2MT 개발이야기Papago/N2MT 개발이야기
Papago/N2MT 개발이야기
 
[226]대용량 텍스트마이닝 기술 하정우
[226]대용량 텍스트마이닝 기술 하정우[226]대용량 텍스트마이닝 기술 하정우
[226]대용량 텍스트마이닝 기술 하정우
 
[224] backend 개발자의 neural machine translation 개발기 김상경
[224] backend 개발자의 neural machine translation 개발기 김상경[224] backend 개발자의 neural machine translation 개발기 김상경
[224] backend 개발자의 neural machine translation 개발기 김상경
 
딥러닝 논문 리뷰 Learning phrase representations using rnn encoder decoder for stati...
딥러닝 논문 리뷰 Learning phrase representations using rnn encoder decoder for stati...딥러닝 논문 리뷰 Learning phrase representations using rnn encoder decoder for stati...
딥러닝 논문 리뷰 Learning phrase representations using rnn encoder decoder for stati...
 
딥러닝 자연어처리 - RNN에서 BERT까지
딥러닝 자연어처리 - RNN에서 BERT까지딥러닝 자연어처리 - RNN에서 BERT까지
딥러닝 자연어처리 - RNN에서 BERT까지
 
제11회공개sw개발자대회 금상 TensorMSA(소개)
제11회공개sw개발자대회 금상 TensorMSA(소개)제11회공개sw개발자대회 금상 TensorMSA(소개)
제11회공개sw개발자대회 금상 TensorMSA(소개)
 
딥러닝 기반의 자연어처리 최근 연구 동향
딥러닝 기반의 자연어처리 최근 연구 동향딥러닝 기반의 자연어처리 최근 연구 동향
딥러닝 기반의 자연어처리 최근 연구 동향
 
[한국어] Neural Architecture Search with Reinforcement Learning
[한국어] Neural Architecture Search with Reinforcement Learning[한국어] Neural Architecture Search with Reinforcement Learning
[한국어] Neural Architecture Search with Reinforcement Learning
 

Similar to MATLAB Programming BASIC @ GIST winter school 2015

Introduction to Fork Join Framework_SYS4U I&C
Introduction to Fork Join Framework_SYS4U I&CIntroduction to Fork Join Framework_SYS4U I&C
Introduction to Fork Join Framework_SYS4U I&Csys4u
 
[21]변화의 시대 : 안드로이드 앱 어떻게 개발할 것인가?
[21]변화의 시대 : 안드로이드 앱 어떻게 개발할 것인가?[21]변화의 시대 : 안드로이드 앱 어떻게 개발할 것인가?
[21]변화의 시대 : 안드로이드 앱 어떻게 개발할 것인가?NAVER Engineering
 
Sonarqube 20160509
Sonarqube 20160509Sonarqube 20160509
Sonarqube 20160509영석 조
 
04.실행환경 교육교재(화면처리)
04.실행환경 교육교재(화면처리)04.실행환경 교육교재(화면처리)
04.실행환경 교육교재(화면처리)Hankyo
 
Implementing_AOP_in_Spring_SYS4U
Implementing_AOP_in_Spring_SYS4UImplementing_AOP_in_Spring_SYS4U
Implementing_AOP_in_Spring_SYS4Usys4u
 
Node.js 시작하기
Node.js 시작하기Node.js 시작하기
Node.js 시작하기Huey Park
 
[IoT] MAKE with Open H/W + Node.JS - 3rd
[IoT] MAKE with Open H/W + Node.JS - 3rd[IoT] MAKE with Open H/W + Node.JS - 3rd
[IoT] MAKE with Open H/W + Node.JS - 3rdPark Jonggun
 
제2회 난공불락 오픈소스 인프라 세미나 Kubernetes
제2회 난공불락 오픈소스 인프라 세미나 Kubernetes제2회 난공불락 오픈소스 인프라 세미나 Kubernetes
제2회 난공불락 오픈소스 인프라 세미나 KubernetesTommy Lee
 
Better Scalable Flexible Soa Platform 0.8.0
Better Scalable Flexible Soa Platform 0.8.0Better Scalable Flexible Soa Platform 0.8.0
Better Scalable Flexible Soa Platform 0.8.0Kidong Lee
 
코드로 바로 해버리는 서버리스 오케스트레이션 - Azure Durable Functions
코드로 바로 해버리는 서버리스 오케스트레이션 - Azure Durable Functions코드로 바로 해버리는 서버리스 오케스트레이션 - Azure Durable Functions
코드로 바로 해버리는 서버리스 오케스트레이션 - Azure Durable FunctionsJongin Lee
 
자바스크립트 함수
자바스크립트 함수자바스크립트 함수
자바스크립트 함수유진 변
 
김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019
김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019
김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019min woog kim
 
Intro to JavaScript - Week 1: Value, Type, Operator
Intro to JavaScript - Week 1: Value, Type, OperatorIntro to JavaScript - Week 1: Value, Type, Operator
Intro to JavaScript - Week 1: Value, Type, OperatorJeongbae Oh
 
Private PaaS with Docker, spring cloud and mesos
Private PaaS with Docker, spring cloud and mesos Private PaaS with Docker, spring cloud and mesos
Private PaaS with Docker, spring cloud and mesos uEngine Solutions
 
[네이버오픈소스세미나] Pinpoint를 이용해서 서버리스 플랫폼 Apache Openwhisk 트레이싱하기 - 오승현
[네이버오픈소스세미나] Pinpoint를 이용해서 서버리스 플랫폼 Apache Openwhisk 트레이싱하기 - 오승현[네이버오픈소스세미나] Pinpoint를 이용해서 서버리스 플랫폼 Apache Openwhisk 트레이싱하기 - 오승현
[네이버오픈소스세미나] Pinpoint를 이용해서 서버리스 플랫폼 Apache Openwhisk 트레이싱하기 - 오승현NAVER Engineering
 
OpenJigWare(V02.00.04)
OpenJigWare(V02.00.04)OpenJigWare(V02.00.04)
OpenJigWare(V02.00.04)Jinwook On
 

Similar to MATLAB Programming BASIC @ GIST winter school 2015 (20)

Introduction to Fork Join Framework_SYS4U I&C
Introduction to Fork Join Framework_SYS4U I&CIntroduction to Fork Join Framework_SYS4U I&C
Introduction to Fork Join Framework_SYS4U I&C
 
[21]변화의 시대 : 안드로이드 앱 어떻게 개발할 것인가?
[21]변화의 시대 : 안드로이드 앱 어떻게 개발할 것인가?[21]변화의 시대 : 안드로이드 앱 어떻게 개발할 것인가?
[21]변화의 시대 : 안드로이드 앱 어떻게 개발할 것인가?
 
Sonarqube 20160509
Sonarqube 20160509Sonarqube 20160509
Sonarqube 20160509
 
(스프링프레임워크 강좌)스프링부트개요 및 HelloWorld 따라하기
(스프링프레임워크 강좌)스프링부트개요 및 HelloWorld 따라하기(스프링프레임워크 강좌)스프링부트개요 및 HelloWorld 따라하기
(스프링프레임워크 강좌)스프링부트개요 및 HelloWorld 따라하기
 
04.실행환경 교육교재(화면처리)
04.실행환경 교육교재(화면처리)04.실행환경 교육교재(화면처리)
04.실행환경 교육교재(화면처리)
 
Implementing_AOP_in_Spring_SYS4U
Implementing_AOP_in_Spring_SYS4UImplementing_AOP_in_Spring_SYS4U
Implementing_AOP_in_Spring_SYS4U
 
Node.js 시작하기
Node.js 시작하기Node.js 시작하기
Node.js 시작하기
 
[IoT] MAKE with Open H/W + Node.JS - 3rd
[IoT] MAKE with Open H/W + Node.JS - 3rd[IoT] MAKE with Open H/W + Node.JS - 3rd
[IoT] MAKE with Open H/W + Node.JS - 3rd
 
제2회 난공불락 오픈소스 인프라 세미나 Kubernetes
제2회 난공불락 오픈소스 인프라 세미나 Kubernetes제2회 난공불락 오픈소스 인프라 세미나 Kubernetes
제2회 난공불락 오픈소스 인프라 세미나 Kubernetes
 
Better Scalable Flexible Soa Platform 0.8.0
Better Scalable Flexible Soa Platform 0.8.0Better Scalable Flexible Soa Platform 0.8.0
Better Scalable Flexible Soa Platform 0.8.0
 
llvm 소개
llvm 소개llvm 소개
llvm 소개
 
코드로 바로 해버리는 서버리스 오케스트레이션 - Azure Durable Functions
코드로 바로 해버리는 서버리스 오케스트레이션 - Azure Durable Functions코드로 바로 해버리는 서버리스 오케스트레이션 - Azure Durable Functions
코드로 바로 해버리는 서버리스 오케스트레이션 - Azure Durable Functions
 
자바스크립트 함수
자바스크립트 함수자바스크립트 함수
자바스크립트 함수
 
김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019
김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019
김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019
 
Cygnus unit test
Cygnus unit testCygnus unit test
Cygnus unit test
 
Intro to JavaScript - Week 1: Value, Type, Operator
Intro to JavaScript - Week 1: Value, Type, OperatorIntro to JavaScript - Week 1: Value, Type, Operator
Intro to JavaScript - Week 1: Value, Type, Operator
 
Matlab guide
Matlab guideMatlab guide
Matlab guide
 
Private PaaS with Docker, spring cloud and mesos
Private PaaS with Docker, spring cloud and mesos Private PaaS with Docker, spring cloud and mesos
Private PaaS with Docker, spring cloud and mesos
 
[네이버오픈소스세미나] Pinpoint를 이용해서 서버리스 플랫폼 Apache Openwhisk 트레이싱하기 - 오승현
[네이버오픈소스세미나] Pinpoint를 이용해서 서버리스 플랫폼 Apache Openwhisk 트레이싱하기 - 오승현[네이버오픈소스세미나] Pinpoint를 이용해서 서버리스 플랫폼 Apache Openwhisk 트레이싱하기 - 오승현
[네이버오픈소스세미나] Pinpoint를 이용해서 서버리스 플랫폼 Apache Openwhisk 트레이싱하기 - 오승현
 
OpenJigWare(V02.00.04)
OpenJigWare(V02.00.04)OpenJigWare(V02.00.04)
OpenJigWare(V02.00.04)
 

More from Jaewook. Kang

190111 tf2 preview_jwkang_pub
190111 tf2 preview_jwkang_pub190111 tf2 preview_jwkang_pub
190111 tf2 preview_jwkang_pubJaewook. Kang
 
Cloud tpu jae_180814
Cloud tpu jae_180814Cloud tpu jae_180814
Cloud tpu jae_180814Jaewook. Kang
 
A Simple Communication System Design Lab #4 with MATLAB Simulink
A Simple Communication System Design Lab #4 with MATLAB SimulinkA Simple Communication System Design Lab #4 with MATLAB Simulink
A Simple Communication System Design Lab #4 with MATLAB SimulinkJaewook. Kang
 
A Simple Communication System Design Lab #3 with MATLAB Simulink
A Simple Communication System Design Lab #3 with MATLAB SimulinkA Simple Communication System Design Lab #3 with MATLAB Simulink
A Simple Communication System Design Lab #3 with MATLAB SimulinkJaewook. Kang
 
A Simple Communication System Design Lab #2 with MATLAB Simulink
A Simple Communication System Design Lab #2 with MATLAB SimulinkA Simple Communication System Design Lab #2 with MATLAB Simulink
A Simple Communication System Design Lab #2 with MATLAB SimulinkJaewook. Kang
 
A Simple Communication System Design Lab #1 with MATLAB Simulink
A Simple Communication System Design Lab #1 with MATLAB Simulink A Simple Communication System Design Lab #1 with MATLAB Simulink
A Simple Communication System Design Lab #1 with MATLAB Simulink Jaewook. Kang
 
Jaewook Kang's Phd final defense @ 20151117
Jaewook Kang's  Phd final defense @ 20151117Jaewook Kang's  Phd final defense @ 20151117
Jaewook Kang's Phd final defense @ 20151117Jaewook. Kang
 
Introduction to Soundlly 2nd screen services and technology: Seminar in 금오공대 ...
Introduction to Soundlly 2nd screen services and technology: Seminar in 금오공대 ...Introduction to Soundlly 2nd screen services and technology: Seminar in 금오공대 ...
Introduction to Soundlly 2nd screen services and technology: Seminar in 금오공대 ...Jaewook. Kang
 

More from Jaewook. Kang (9)

190111 tf2 preview_jwkang_pub
190111 tf2 preview_jwkang_pub190111 tf2 preview_jwkang_pub
190111 tf2 preview_jwkang_pub
 
Cloud tpu jae_180814
Cloud tpu jae_180814Cloud tpu jae_180814
Cloud tpu jae_180814
 
Life is stair-like
Life is stair-likeLife is stair-like
Life is stair-like
 
A Simple Communication System Design Lab #4 with MATLAB Simulink
A Simple Communication System Design Lab #4 with MATLAB SimulinkA Simple Communication System Design Lab #4 with MATLAB Simulink
A Simple Communication System Design Lab #4 with MATLAB Simulink
 
A Simple Communication System Design Lab #3 with MATLAB Simulink
A Simple Communication System Design Lab #3 with MATLAB SimulinkA Simple Communication System Design Lab #3 with MATLAB Simulink
A Simple Communication System Design Lab #3 with MATLAB Simulink
 
A Simple Communication System Design Lab #2 with MATLAB Simulink
A Simple Communication System Design Lab #2 with MATLAB SimulinkA Simple Communication System Design Lab #2 with MATLAB Simulink
A Simple Communication System Design Lab #2 with MATLAB Simulink
 
A Simple Communication System Design Lab #1 with MATLAB Simulink
A Simple Communication System Design Lab #1 with MATLAB Simulink A Simple Communication System Design Lab #1 with MATLAB Simulink
A Simple Communication System Design Lab #1 with MATLAB Simulink
 
Jaewook Kang's Phd final defense @ 20151117
Jaewook Kang's  Phd final defense @ 20151117Jaewook Kang's  Phd final defense @ 20151117
Jaewook Kang's Phd final defense @ 20151117
 
Introduction to Soundlly 2nd screen services and technology: Seminar in 금오공대 ...
Introduction to Soundlly 2nd screen services and technology: Seminar in 금오공대 ...Introduction to Soundlly 2nd screen services and technology: Seminar in 금오공대 ...
Introduction to Soundlly 2nd screen services and technology: Seminar in 금오공대 ...
 

MATLAB Programming BASIC @ GIST winter school 2015

  • 1. GIST 정보통신공학과 Winter school 프로그래밍 활용 교육: MATLAB 1일차 강 재 욱 jwkkang@gist.ac.kr School of Information and Communications Feb. 2015 1 © 2015 Jaewook Kang All Rights Reserved
  • 2. GIST 정보통신공학과 Winter School 2015, 강재욱 강 사 소 개 § GIST 정보통신공학과 박사과정 § 센서통신 연구실 (김기선 교수) § Student Chair in IEEE student branch (since 2014 Apr.) § 연구분야: § Belief propagation 기반의 compressive sensing 복구 알고리즘 § 역 선형 변환을 위한 Approximate message-passing 알고리즘 § 기계학습 기반의 무선통신 수신기 설계 2 § 대표논문: Jaewook Kang, Heung-No Lee, Kiseon Kim, "Bayesian Hypothesis Test using Nonparametric Belief Propagation for Noisy Sparse Recovery," IEEE Trans. on Signal process., vol. 63, no. 4, pp. 935-948, Feb. 2015 § Contact point: Lab. phone: +82-62-715-2264 E-mail : jwkkang@gist.ac.kr Hompage: https://sites.google.com/site/jwkang10/ Jaewook Kang (강재욱)
  • 3. GIST 정보통신공학과 Winter School 2015, 강재욱 강의 일정 3 일 정 시간 내 용 강 사 Day 1 (2/11) Lab. 1 3 - MATLAB 프로그래밍 일반 - Vectorized 코딩 1 강재욱 Lab. 2 3 - 국내외 산업분야 활용 사례 소개 - 수치해석에서 테크니컬 컴퓨팅까지 - 공학기초를 위한 MATLAB과 Symbolic Math 활용법 Mathwork 초빙강사 Day 2 (2/12) Lab. 3 3 - Vectorized 코딩 2 - 고급 MATLAB 함수 활용 강재욱 Lab. 4 3 - DATA Acquisition with Labview 송하준 Day 3 (2/13) Lab. 5 3 - MATLAB을 이용한 통신시스템 모델링 1 장재혁 Lab. 6 3 - MATLAB을 이용한 통신시스템 모델링 2
  • 4. GIST 정보통신공학과 Winter School 2015, 강재욱 목 차 일 정 내 용 1일차 (3시간) 1. MATLAB Programs General 1. MATLAB Program Organization 2. User-defined function 3. Variable scope 4. Debugging Techniques 2. Vectorized Code 1. Loops with Vectors and Matrices 2. Operations on Vectors and Matrices 3. Vectors and Matrices as Function Arguments 2일차 (3시간) 1. Vectorized Code 4. Logical Vectors 5. Vectorizing Code 2. Advanced MATLAB Functions 1. Anonymous Functions 2. Uses of Function Handles 3. Variable Number of Arguments 4
  • 6. GIST 정보통신공학과 Winter School 2015, 강재욱 Why MATLAB ? v MATLAB 장점 § “수식 to 프로그램” 이식이 간편함 § Vectorized 코딩: 빠르고 간단한 벡터/행렬 기반 프로그래밍 § 다양한 MATLAB 함수: 통계, 확률, 신호처리 § 강력한 함수/데이터의 도시화 기능 6 MATLAB Mathmetica - MathWork (1984) - 공학시뮬레이션 - 수치적 계산& 시뮬레이션 - 계산효율성 좋음 -Wolfram (1988) - 공학시스템의 수학적 모델링 - 심볼릭 연산!: 수학기호를 그 대로 연산 - 계산효율성 보통
  • 7. 1. MATLAB Programs General 1. MATLAB Program Organization 2. User-defined function 3. Variable scope 4. Debugging Techniques 7
  • 8. GIST 정보통신공학과 Winter School 2015, 강재욱 MATLAB Program Organization v MATLAB 파일 (m-file)의 종류 – Script 파일: • MATLAB statement의 모음이 저장된 m-file • 해당 M-file을 실행하면 그안에 있는 모든 statement가 실행됨 – User-define Function 파일: • 사용자가 정의한 작업을 수행하고 특정값을 리턴하는 함수가 저장된 m-file • 해당 함수는 MATLAB 커맨드 윈도우나 다른 script 파일에서 호출하여 사용이 가능함 8 함수 파일 스크립트 파일
  • 9. GIST 정보통신공학과 Winter School 2015, 강재욱 MATLAB Program Organization v MATLAB 프로그램의 구성 – MATLAB 프로그램은 다양한 “MATLAB 함수 파일”과, 그 함수들을 호출하는 “Script 파일”로 구성된다. v Modular 프로그래밍 – 전체작업을 여러 개의 작은 모듈로 나누고, 각 모듈을 함수로 구현하여 프로그램을 구현하는 방식 (cf. divide and conquer) – 여기서 Script함수가 main program이 된다. (cf. C언어 main 함수) 9 % This m-file is a script file for the Main Program func_for_task1(); % function cal l for the task 1 func_for_task2(); % function cal l for the task 2 … Func_for_taskN(); % function cal l for the task N
  • 10. GIST 정보통신공학과 Winter School 2015, 강재욱 User-define Functions v 정의: 사용자 정의 한 작업을 수행하는 함수 – 임의의 script파일이나 command window에서 호출가능 v ex1: function_name.m 10 % Function Header function [output_arguments]= function_name(input_arguments) % body of the function end § 모든작업 statement를 포함 § 모든 출력인자에 값을 할당해야함 § 함수이름은 저장하는 M- file이름과 동일하게 § 여러 개의 입력인자의 구분은 컴마“,” 사용
  • 11. GIST 정보통신공학과 Winter School 2015, 강재욱 User-define Functions v Practice1: 넓이 & 원주 계산 함수 (areacirc.m) 11 % Function Header function [area, circum] = areacirc(rad) % body of the function end
  • 12. GIST 정보통신공학과 Winter School 2015, 강재욱 User-define Functions v Practice1: 넓이 & 원주 계산 함수 (areacirc.m) 12 % Function Header function [area, circum] = areacirc(rad) % areacirc returns the area and % the circumference of a circle % Format: areacirc(radius) area = pi * rad * rad; circum = 2 * pi * rad; end § “help”를 통해서 나오는 함수에 대한 설명 주석 § 두개의 출력인자에 값 할당
  • 13. GIST 정보통신공학과 Winter School 2015, 강재욱 User-define Functions v ex2: 입력인자(input arguments)가 없는 함수 (stringprompt.m) v ex3: 출력인자(output arguments)가 없는 함수 (printem.m) 13 function outstr = stringprompt() % Also, “function outstr=stringprompt()” is fine. % 문자열을 입력 받고 그 값을 리턴하는 함수 disp('When prompted, enter a string of any length.'); outstr = input('Enter the string here: ', 's'); end § “()” 괄호 안을 비워둠 또는 괄호 제거 가능 function printem(a,b) % 두 입력 인자 값을 출력하는 함수 disp(sprintf('The first number is %.1f and the second is %.1fn',a,b)); end § 출력인자가 없음 § 출력인자 값 할당
  • 14. GIST 정보통신공학과 Winter School 2015, 강재욱 User-define Functions v Practice2: 넓이 & 원주 계산 프로그램 (calcareacirc.m) – Modular 프로그램밍 방식을 이용하여 다음 작업을 수행하는 프로그램을 작성하시오 • Task 1: 반지름값 입력 받기 (input 함수 이용) • Task 2: 넓이 & 원주 계산하기 (practice 1 참조) • Task 3: 계산한 값 도시 하기 (disp() 함수 이용) 14
  • 15. GIST 정보통신공학과 Winter School 2015, 강재욱 User-define Functions v Practice2: 넓이 & 원주 계산 프로그램 (calcareacirc.m) – Modular 프로그램밍 방식을 이용하여 다음 작업을 수행하는 프로그램을 작성하시오 • Task 1: 반지름값 입력 받기 (input 함수 이용) • Task 2: 넓이 & 원주 계산하기 (practice 1 참조) • Task 3: 계산한 값 도시 하기 (disp() 함수 이용) % This script prompts the user for the radius of a circle, % calls a function to calculate and return both the area % and the circumference, and prints the results % It ignores units and error-checking for simplicity radius =input('Please enter the radius of the circle: '); [area circ] = areacirc(radius); disp(sprintf('For a circle with a radius of %.1f,n', radius)); disp(sprintf('the area is %.1f and the circumference is %.1fn',area, circ)); 15
  • 16. GIST 정보통신공학과 Winter School 2015, 강재욱 16 Variable Scope v Local variable (지역변수) – 호출된 함수 안에서 정의된 변수 – 해당 함수가 호출 됐을 때에 제한되어 접근 가능 – MATLAB workspace에서 보이지 않음 v Global variable (전역변수) – Workspace 뿐만 아니라 호출된 함수 안에서도 접근 가능한 변수 – -global 키워드로 사전 선언 필요함 하고 함수 안에서 사용시 global 선언이 필요함 v ex4: mysum.m + who (workspace변수를 도시하는 함수) 16 function runsum = mysum(vec) % mysum returns the sum of a vector runsum = 0; for i=1:length(vec) runsum = runsum + vec(i); end end >> clear >> who >> disp(mysum([5 4 1])); 10 >> who § Worksparce에 변수 없음 § 함수 실행 이후에도 Worksparce에 변수 없음
  • 17. GIST 정보통신공학과 Winter School 2015, 강재욱 Variable Scope v ex5: mysumscript.m + who (workspace변수를 도시하는 함수) 17 % mysumscript.m vec=1:5 runsum = 0; for i=1:length(vec) runsum = runsum + vec(i); end disp(runsum) >> clear >> who >> mysumscript 15 >> who Your variables are: i runsum vec § Script 실행 § Script 실행 후 workspace에 변수 생성 § Script 실행 전 workspace에 변수 없음 17
  • 18. GIST 정보통신공학과 Winter School 2015, 강재욱 Variable Scope v Persistent variables – persistent로 정의된 변수는, 함수종료시 값이 clear되지 않고, 다음 함수호출까지 이전 함수에서의 값을 유지한다. – Persistent 변수를 초기화 하기위해서는 “clear” 명령어를 사용 v ex6: Counting number (func1.m, func2.m) function func1 % func1 increments a normal variable "count" count = 0; count = count +1; disp(sprintf('The value of count is %dn',count)); end function func2 % func2 increments a persistent variable "count" persistent count if isempty(count) count =0; end count = count + 1; disp(sprintf('The value of count is %dn',count)); end § Persistent 변수 “count” § 일반 변수 “count” 18
  • 20. GIST 정보통신공학과 Winter School 2015, 강재욱 Debugging Techniques v프로그램 오류의 종류 – 1) Syntax errors: MATLAB language의 오류가 원인이 되어 발생 à MATLAB compiler에서 처리됨 – 2) Runtime error: 프로그램이 실행되는 동안 발생하는 오류 à 프로그램이 실행 도중에 오류로 작업을 멈춤 – 3) Logical errors: 프로그램어의 논리적추론이 잘못되어 발생à 가장 찾기 어려움 20 >>mystr = 'how are you; ??? mystr = 'how are you; Error: A MATLAB string constant is not terminated properly. >> vec = 3:5; >> for i = 1:4 disp(vec(i)); end 3 4 5 ??? Attempted to access vec(4); index out of bounds because numel(vec)= 3. Error in => runtimeEx at 6 disp(vec(i))
  • 21. GIST 정보통신공학과 Winter School 2015, 강재욱 Debugging Techniques vDebugging 기법 1: Tracing – Loop (“for or “while”)나 분기문 (“if” or “switch”)을 추적하는 기법 v Ex7) 변수값의 범위 판별 (testifelse.m) 21 >> testifelse(4) In middle of range >> testifelse(7) In middle of range >> testifelse(-2) In middle of range function testifelse(x) % testifelse will test the debugger if 3 < x < 6 disp('In middle of range') else disp('Out of range') end end § A Logical error!
  • 22. GIST 정보통신공학과 Winter School 2015, 강재욱 Debugging Techniques vDebugging 기법 1: Tracing v Ex8) echo 함수의 사용 – Echo()는 실행되는 statement 내용과 결과를 모두 도시한다. 22 >> echo testifelse on >> testifelse(-2) % This function will test the debugger if 3 < x < 6 disp('In middle of range') In middle of range end § If문에 문제가 있음을 알수 있음
  • 23. GIST 정보통신공학과 Winter School 2015, 강재욱 Debugging Techniques vDebugging 기법 2: Breakingpoint의 설정 v Ex9) dbstop()&dbcont() 함수의 사용 – 함수 실행 도중 Breakingpoint를 만들어 중간시점에서 코드를 점검할 수 있다. 23 >> dbstop testifelse 5 >> testifelse(-2) 5 disp('In middle of range') K>> x X = -2 K>> 3 < x ans = 0 K>> 3 < x < 6 ans = 1 K>> dbcont In middle of range end § testifelse 함수 5번째 라인에 breakingpoint를 설정 § testifelse 함수 5번째 라인 § Breakingpoint 종료
  • 24. GIST 정보통신공학과 Winter School 2015, 강재욱 Debugging Techniques vDebugging 기법 2: Breakingpoint의 설정 v Ex9) dbstop()&dbcont() 함수의 사용 – 함수 실행 도중 Breakingpoint를 만들어 중간시점에서 코드를 점검할 수 있다. 24 >> dbstop testifelse 5 >> testifelse(-2) 5 disp('In middle of range') K>> x x = -2 K>> 3 < x ans = 0 K>> 3 < x < 6 ans = 1 K>> dbcont In middle of range end § 오류의 이유는 if문의 조건 설정이 잘못됨 § 3< x <6 은 complier가 (3 < x ) < 6로 이해 § 즉 결과는 è ( 3 < -2 ) <6 è 0 < 6 è 1 § 결과적으로, 항상 “in middle of range” 가 출력됨
  • 25. 2. Vectorized Code 1. Loops with Vectors and Matrices 2. Operations on Vectors and Matrices 3. Vectors and Matrices as Function Arguments 25
  • 26. GIST 정보통신공학과 Winter School 2015, 강재욱 Loops with Vectors and Matrices v MATLAB에서는 벡터/행렬 단위의 계산이 가능함 – 모든 연산자에 대해서 성립 – 벡터/행렬의 각 항에 접근하기 위한 loop가 필요없음 v Ex10) vectorized coding with scalar 26 >> v=[3 7 2 1] >> for i = 1:length(v) v(i) = v(i) * 3; end >> v v = 9 21 6 3 % MATLAB에서만 가능함 >> v=[3 7 2 1] >> v=v*3 v = 9 21 6 3 Conventional coding Vectorized coding § Loop가 필요없음
  • 27. GIST 정보통신공학과 Winter School 2015, 강재욱 Operations on Vectors and Matrices v Array operation 1 – 덧셈 ( + ) /뺄셈( - ) – Term by term or element by element operation v Ex11) array operation: 덧셈 27 >> v1 = 2:5 v1 = 2 3 4 5 >> v2 = [33 11 5 1] v2 = 33 11 5 1 >> v1 + v2 ans = 35 14 9 6 >> mata = [5:8; 9:-2:3] mata = 5 6 7 8 9 7 5 3 >> matb = reshape(1:8,2,4) matb = 1 3 5 7 2 4 6 8 >> mata - matb ans = 4 3 2 1 7 3 1 5 § 1:8까지를 2by4 행렬로 만들어주는 함수
  • 28. GIST 정보통신공학과 Winter School 2015, 강재욱 Operations on Vectors and Matrices v Array operation 2 –지수셈 (.^) – Term by term or element by element operation v Ex12) array operation: 지수셈 – 요소단위로 연산을 하는 경우 연산자 앞에 반드시 ‘.’ dot이 필요하다 즉 (.^). 28 >> v = [3 7 2 1]; >> v ^ 2 ??? Error using ==> mpower Inputs must be a scalar and a square matrix. To compute elementwise POWER, use POWER (.^) instead. >> v .^ 2 ans = 9 49 4 1
  • 29. GIST 정보통신공학과 Winter School 2015, 강재욱 Operations on Vectors and Matrices v Array operation 3 – 곱셈 (.*), 나눗셈 ( ./ ), – Term by term or element by element operation v Ex13) array operation: 곱셈&나눗셈 - 연산자 앞에 반드시 ‘.’ dot이 필요하다 즉 (.*), (./). 29 >> v1 = 2:5 v1 = 2 3 4 5 >> v2 = [33 11 5 1] v2 = 33 11 5 1 >> v1 .* v2 ans = 66 33 20 5 >> mata = [5:8; 9:2:3] mata = 5 6 7 8 9 7 5 3 >> matb = reshape(1:8, 2,4) matb = 1 3 5 7 2 4 6 8 >> mata ./ matb ans = 5.0000 2.0000 1.4000 1.1429 4.5000 1.7500 0.8333 0.3750
  • 30. GIST 정보통신공학과 Winter School 2015, 강재욱 Operations on Vectors and Matrices vPractice 3: array operation – Create a vector variable and add 2 to every element in it. – Create a matrix variable and divide every element by 3. – Create a matrix variable and square every element. 30
  • 31. GIST 정보통신공학과 Winter School 2015, 강재욱 Vectors and Matrices as Function Arguments v MATLAB에서는 벡터&행렬을 입력인자로 전달 할 수 있다. – 함수의 출력인자와 입력인자는 같은 사이즈의 벡터/행렬이다. v Ex14) MATLAB bulit-in 함수 with vector input arguments 31 >> vec = 2:1 vec = 2 1 0 1 >> sinvec = sin(vec) sinvec = 0.9093 0.8415 0 0.8415 >> mat = [0 4 -3; -1 0 2] mat = 0 4 3 1 0 2 >> sign(mat) ans = 0 1 1 1 0 1
  • 32. GIST 정보통신공학과 Winter School 2015, 강재욱 Vectors and Matrices as Function Arguments v Ex15) User-define 함수 with vector input arguments (calcarea.m) v 함수 calcarea()을 어떻게 수정해야 하는가? 32 function area = calcarea(rad) % calcarea calculates the area of a circle % Returns the area area = pi * rad * rad; end >> calcarea(1:3) ??? Error using ==> mtimes Inner matrix dimensions must agree. Error in ==> calcarea at 6 area ¼ pi * rad * rad;
  • 33. GIST 정보통신공학과 Winter School 2015, 강재욱 Vectors and Matrices as Function Arguments v Ex16) User-define 함수 with vector input arguments (calcarea.m) v 함수 calcarea()을 어떻게 수정해야 하는가? 33 function area = calcarea(rad) % calcarea calculates the area of a circle % Returns the area area = pi * rad * rad; end >> calcarea(1:3) ??? Error using ==> mtimes Inner matrix dimensions must agree. Error in ==> calcarea at 6 area ¼ pi * rad * rad; function area = calcareaii(rad) % calcarea calculates the area of a circle % The input argement can be a vector of radii % Returns the area area = pi * rad. * rad; %We can also use area = pi * rad. ^2; end
  • 34. GIST 정보통신공학과 Winter School 2015, 강재욱 Warping up – Day 1 1. MATLAB Programs General 1. MATLAB Program Organization 2. User-defined function 3. Variable scope 4. Debugging Techniques 2. Vectorized Code 1. Loops with Vectors and Matrices 2. Operations on Vectors and Matrices 3. Vectors and Matrices as Function Arguments 34
  • 35. GIST 정보통신공학과 Winter school 프로그래밍 활용 교육: MATLAB 2일차 강 재 욱 jwkkang@gist.ac.kr School of Information and Communications Feb. 2015 35 © 2015 Jaewook Kang All Rights Reserved
  • 36. GIST 정보통신공학과 Winter School 2015, 강재욱 강의 일정 36 일 정 시간 내 용 강 사 Day 1 (2/11) Lab. 1 3 - MATLAB 프로그래밍 일반 - Vectorized 코딩 1 강재욱 Lab. 2 3 - 국내외 산업분야 활용 사례 소개 - 수치해석에서 테크니컬 컴퓨팅까지 - 공학기초를 위한 MATLAB과 Symbolic Math 활용법 Mathwork 초빙강사 Day 2 (2/12) Lab. 3 3 - Vectorized 코딩 2 - 고급 MATLAB 함수 활용 강재욱 Lab. 4 3 - DATA Acquisition with Labview 송하준 Day 3 (2/13) Lab. 5 3 - MATLAB을 이용한 통신시스템 모델링 1 장재혁 Lab. 6 3 - MATLAB을 이용한 통신시스템 모델링 2
  • 37. GIST 정보통신공학과 Winter School 2015, 강재욱 목 차 일 정 내 용 1일차 (3시간) 1. MATLAB Programs General 1. MATLAB Program Organization 2. User-defined function 3. Variable scope 4. Debugging Techniques 2. Vectorized Code 1. Loops with Vectors and Matrices 2. Operations on Vectors and Matrices 3. Vectors and Matrices as Function Arguments 2일차 (3시간) 1. Vectorized Code 4. Logical Vectors 5. Vectorizing Code 2. Advanced MATLAB Functions 1. Anonymous Functions 2. Uses of Function Handles 3. Variable Number of Arguments 37
  • 38. 2. Vectorized Code 4. Logical Vectors 5. Vectorizing codes 38
  • 39. GIST 정보통신공학과 Winter School 2015, 강재욱 Logical Vectors v 정의: 논리값(true or false)을 요소로 가지는 벡터 v Ex17) 벡터의 논리 연산 39 >> vec=[5 9 3 4 6 11]; >> isg = vec <5 0 1 0 0 1 1 >> whos Name Size Bytes Class isg 1x6 6 logical array vec 1x6 48 double array >> sum(isg) ans = 3 >> vec(isg) ans = 9 6 11 § ‘1’ or ‘0’로만 표현됨 § Low memory 사용 § Sum()으로 vec<5 을 만족한 요소의 수를 구할수 있음 § Logical vector는 벡터변수의 index로 사용이 가능함
  • 40. GIST 정보통신공학과 Winter School 2015, 강재욱 Logical Vectors v Ex 18) Logical vector변수의 선언 – Logical () , false(), true()함수를 사용하여 logical vector를 선언할 수 있다. 40 >> logical(zeros(2)) ans = 0 0 0 0 >> logical(ones(1,5)) ans = 1 1 1 1 1 >> false(2) ans = 0 0 0 0 >> true(1,5) ans = 1 1 1 1 1 § logical 함수는 double값을 logical datatype으로 변환 § false() 와 true()를 이용하면 더욱 빠른 생성이 가능함
  • 41. GIST 정보통신공학과 Winter School 2015, 강재욱 Logical Vectors v Ex 19) Logical built-in 함수 ( any() & all() ) – any()와 all() 함수의 사용: – any() 함수는 입력인자 vec의 요소가 하나라도 nonzero인 경우 true를 리턴 – all() 함수는 입력인자 모두가 nonzero인 경우 true를 리턴 41 >> vec1 = [1 3 1 1 2]; >> any(vec1) ans = 1 >> all(vec1) ans = 1 >> vec2 = [1 1 0 1] vec2 = 1 1 0 1 >> any(vec2) ans = 1 >> all(vec2) ans = 0 § vec의 요소는 모두 nonzero인 경우 § 적어도 하나의 nonzero를 포함함으로 any()는 ‘true’를 리턴 § 모두 nonzero가 아니므로 all()는 ‘false’를 리턴
  • 42. GIST 정보통신공학과 Winter School 2015, 강재욱 Logical Vectors v Ex 20) Logical built-in 함수 ( find() ) – find() 함수의 사용: 입력 조건문을 만족시키는 요소의 인덱스와 값을 리턴 42 >> vec = [5 3 6 7 2] vec = 5 3 6 7 2 >>[index, value]= find(vec > 5) index = 3 4 value = 6 7
  • 43. GIST 정보통신공학과 Winter School 2015, 강재욱 Logical Vectors v Practice 4: – vec=[ 11 – 33 2 8 -4 25]; – 위의 vec에서 find()함수를 이용하여 음수의 항을 제거 하시오 43
  • 44. GIST 정보통신공학과 Winter School 2015, 강재욱 Logical Vectors v Practice 5: – Task 1: randint()와 함수를 이용하여 [1, 100]의 범위에서 100 by 1 정수 벡터 vec1를 생성 – Task 2: vec1벡터에서 “50 보다 큰 값을 가지는 항”에 대한 index 벡터 생성 – Task 3: index벡터를 이용하여 vec1벡터에서 “50 보다 큰 값을 가지는 항”을 추출하여 새로운 벡터 vec2를 생성 44
  • 45. GIST 정보통신공학과 Winter School 2015, 강재욱 Logical Vectors v Ex 21) Logical built-in 함수 ( isequal() ) – isequal() 함수의 사용: 두 벡터가 같은 벡터인지 확인한다. – isequal ()함수와 “==“연산자와의 차이 45 >> vec1 = [1 3 4 2 99]; >> vec2 = [1 2 4 3 99]; >> vec1 == vec2 ans = 1 0 1 0 1 >> all(vec1 == vec2) ans = 0 >> isequal(vec1,vec2) ans = 0 § “==“연산자는 elem by elem으로 비교 § isequal() 함수는 벡터단위로 비교
  • 46. GIST 정보통신공학과 Winter School 2015, 강재욱 Vectorizing codes v 정의: MATLAB에서 제공 벡터/행렬 연산과 built-in 함수들을 이용하여, 효율적으로 다시 프로그래밍 한 코드 – Array operation : (.*), ,(./), (.^) – Built-in functions: any() all() find(), and so on… – Preallocation of vectors: zeros(), ones(), and so on.. 46
  • 47. GIST 정보통신공학과 Winter School 2015, 강재욱 Vectorizing codes v Ex22) 행렬의 각 요소의 부호를 알아보는 함수 ( signum.m) 47 function outmat =signum(mat) % signum imitates the sign function [r c] = size(mat); for i = 1:r for j = 1:c if mat(i,j) > 0 outmat(i,j) = 1; elseif mat(i,j) == 0 outmat(i,j) = 0; else outmat(i,j) = -1; end end end end >> mat = [0 4 -3; -1 0 2] mat = 0 4 -3 -1 0 2 >> signum(mat) ans = 0 1 -1 -1 0 1
  • 48. GIST 정보통신공학과 Winter School 2015, 강재욱 Vectorizing codes v Ex22) 행렬의 각 요소의 부호를 알아보는 함수 ( signum.m) – 동일연산이 MATLAB built-in 함수인 sign()을 사용하여 효율적으로 수행될 수 있음 – 대부분의 수학연산 함수, sqrt(),exp(),log(),가 벡터/행렬 연산을 지원함 48 function outmat =signum(mat) % signum imitates the sign function [r c] = size(mat); for i = 1:r for j = 1:c if mat(i,j) > 0 outmat(i,j) = 1; elseif mat(i,j) == 0 outmat(i,j) = 0; else outmat(i,j) = -1; end end end end >> mat = [0 4 -3; -1 0 2] mat = 0 4 -3 -1 0 2 >> signum(mat) ans = 0 1 -1 -1 0 1
  • 49. GIST 정보통신공학과 Winter School 2015, 강재욱 Vectorizing codes v Ex23) diff(x) 함수의 사용 – 입력벡터 x에 대하여 𝑋" − 𝑋"$%   ∀𝑖 ∈ {2, . . . , 𝑁} 을 리턴 – 출력벡터은 따라서 N-1의 길이를 가진다. 49 >> diff([4 7 15 32]) ans = 3 8 17 >> diff([4 7 2 32]) ans = 3 5 30
  • 50. GIST 정보통신공학과 Winter School 2015, 강재욱 Vectorizing codes v Ex24) CPU runtime measuring using tic/toc (fortictoc.m) 50 >> fortictoc Elapsed time is 0.088591 seconds. % fortictoc.m tic mysum = 0; for i = 1:20000000 mysum = mysum + i; end toc
  • 51. GIST 정보통신공학과 Winter School 2015, 강재욱 Vectorizing codes v Ex25) Preallocation (tictocprealloc.m) 51 >> tictocprealloc No preallocation Elapsed time is 0.070526 seconds. Preallocation Elapsed time is 0.001177 seconds.. % tictocprealloc.m shows the timing difference between preallocating a vector vs. not clear disp('No preallocation') tic for i = 1:10000 x(i) = sqrt(i); end toc disp('Preallocation') tic y =zeros(1,10000); for i = 1:10000 y(i) = sqrt(i); end toc § Preallocation을 사용하지 않는 경우 § Preallocation을 사용하는 경우
  • 52. 3. Advanced MATLAB Functions 1. Anonymous Functions 2. Uses of Function handles 3. Variable Number of Arguments 52
  • 53. GIST 정보통신공학과 Winter School 2015, 강재욱 Anonymous Function v Anonymous Function – 따로 m-file로 저장하지 않고, 단순 연산을 one-line으로 정의하여 사용하는 함수 • Function handle: 함수호출 시 사용하는 reference • Arguments: 입력인자 • Function body: 함수연산 내용 • v Ex 26) 원 넓이 구하는 함수 (ver. anonymous function) 53 fnhandle= @ (arguments) functionbody; cirarea= @(rad) pi*rad .^2; >> cirarea(4) ans = 50.2655 >> cirarea(1:4) ans = 3.1416 12.5664 28.2743 50.2655. § (.^)을 사용하여 벡터연산도 가능함
  • 54. GIST 정보통신공학과 Winter School 2015, 강재욱 Anonymous Function v Anonymous Function – M-file 함수와는 달리 입력인자가 없는 경우에도 괄호 ()를 포함 해야 한다. – 괄호 () 를 포함하지 않는 호출의 경우 function handle은 함수 정의를 보여준다. v Practice 6: Anonymous function을 사용하여 원주를 계산하는 프로그램을 작성하시오 54 >> prtran =@ () disp( sprintf('%.2fn',rand) ); >> prtran() 0.95 >> prtran Prtran = @ () disp( sprintf('%.2fn',rand) )
  • 55. GIST 정보통신공학과 Winter School 2015, 강재욱 Uses of Function handles v Function handle은 일반함수에 대해서도 생성될 수 있다. – “@” 는 일반함수로 부터 Function handle을 얻는 연산자임 55 >> facth = @factorial; >> facth (5) ans = 120 § facth는 built-in 함수 factorial()의 function handle임 § function handle을 사용한 함수호출
  • 56. GIST 정보통신공학과 Winter School 2015, 강재욱 Uses of Function handles v Function handle을 사용하는 이유 – Function handle를 다른 함수의 입력인자로 전달하기 위해서임 – 입력 Function handle에 따라서 다른 작업수행을 하는 함수를 정의가능 v Ex 27) Function handle을 입력인자로 받는 함수 (fnfnexamp.m) 56 function fnfnexamp(funh) % fnfnexamp receives the handle of a function % and plots that function of x (which is 1:.25:6) x =1:.25:6; y = funh(x); plot(x,y,'ko') xlabel('x') ylabel('fn(x)') title(func2str(funh)) end § 입력인자 function handle에 따라서 다른 동작을 수행 § 작업수행결과를 plot § 입력인자에 function handle
  • 57. GIST 정보통신공학과 Winter School 2015, 강재욱 Uses of Function handles v Function handle을 사용하는 이유 – Function handle를 다른 함수의 입력인자로 전달하기 위해서임 – 입력 Function handle에 따라서 다른 작업수행을 하는 함수를 정의가능 v Ex 27) Function handle을 입력인자로 받는 함수 (fnfnexamp.m) 57 >> fnfnexamp(@sin) >> fnfnexamp(@cos) § 입력인자 function handle에 따라서 다른 동작을 수행 § 입력인자에 function handle
  • 58. GIST 정보통신공학과 Winter School 2015, 강재욱 Variable Number of Arguments v Variable number of input arguments – varargin : 입력인자를 저장하는 cell array – nargin: 입력인자의 개수 v Ex 28) 원의 넓이는 계산하는 함수 (varargin.m) – 첫째 입력인자는 반지름 – 두째 입력인자는 단위를 정한다. – 함수에 첫째 입력인자만 전달되는 경우 default로 ‘feet’ 단위로 계산 – 두번째 입력인자가 ‘i’인 경우 ‘inche’ 단위로 계산 58
  • 59. GIST 정보통신공학과 Winter School 2015, 강재욱 Variable Number of Arguments v Ex 28) 원의 넓이는 계산하는 함수 함수 (areafori.m) 59 function area = areafori(varargin) % areafori returns the area of a circle in feet % The radius is passed, and potentially the unit of % inches is also passed, in which case the result will be % given in inches instead of feet n = nargin; % number of input arguments radius = varargin{1}; % Given in feet by default if n ==2 unit = varargin{2}; % if inches is specified, convert the radius if unit == 'i' radius = radius * 12; end end area = pi * radius .^ 2; end § 입력인자가 2개고 두째인자가 ‘i'인 경우 inche로 변환
  • 60. GIST 정보통신공학과 Winter School 2015, 강재욱 Variable Number of Arguments v Ex 28) 원의 넓이는 계산하는 함수 함수 (areafori.m) v Practice 7: 등비수열의 합 계산 함수 1 + 𝑟 + 𝑟2 + 𝑟3 + 𝑟4 +⋅⋅⋅ +𝑟6 – 첫째인자: r의 값 – 둘째인자: n의 값 – 리턴: 합의 값 – 둘째 인자가 없는경우 n을 [5,30]에서 랜덤하게 발생해서 계산 60 >> areafori(3) ans = 28.2743 >> areafori(1,'i') ans = 452.3893
  • 61. GIST 정보통신공학과 Winter School 2015, 강재욱 Variable Number of Arguments v Variable number of output arguments – varargout : 출력인자를 저장하는 cell array – nargout: 출력인자의 개수 v Ex 29) 입력의 데이터타입과 사이즈를 리턴하는 함수 (typesize.m) – 입력인자가 스칼라인경우 ‘s’를 출력 – 입력인자가 벡터인 경우 ‘v’를 출력하고 길이를 출력 – 입력인자가 행렬인 경우 ‘m’을 출력하고 ‘행’/’열’ 길이를 출력 61
  • 62. GIST 정보통신공학과 Winter School 2015, 강재욱 Variable Number of Arguments v Ex 29) 입력의 데이터타입과 사이즈를 리턴하는 함수 (typesize.m) 62 function [arrtype, varargout] = typesize(inputval) % typesize returns a character 's' for scalar, 'v' % for vector, or 'm' for matrix input argument % also returns length of a vector or dimensions of matrix [r c ] = size(inputval); if r==1 && c==1 arrtype = 's'; elseif r==1 || c==1 arrtype ='v'; varargout{1} = length(inputval); else arrtype = 'm'; varargout{1} = r; varargout{2} = c; end end § 스칼라인 경우 -‘s’만 출력 § 벡터인 경우 - ‘v’출력 -길이 출력 § 행렬인 경우 - ‘m’ 출력 - 행 길이 출력 - 열 길이 출력
  • 63. GIST 정보통신공학과 Winter School 2015, 강재욱 Variable Number of Arguments v Ex 29) 입력의 데이터타입과 사이즈를 리턴하는 함수 (typesize.m) 63 >> typesize(5) ans = s >> [arrtype, len] = typesize(4:6) arrtype = v len = 3 >> [arrtype, r, c] = typesize([4:6;3:5]) arrtype = m r = 2 c = 3 § 스칼라인 경우 -‘s’만 출력 § 벡터인 경우 - ‘v’출력 -길이 출력 § 행렬인 경우 - ‘m’ 출력 - 행 길이 출력 - 열 길이 출력
  • 64. GIST 정보통신공학과 Winter School 2015, 강재욱 Variable Number of Arguments v Ex 30) 출력인자 개수에 따라 추가적인 정보를 제공하는 함수(mysize.m) 64 function [row col varargout] = mysize(mat) % mysize returns dimensions of input argument % and possibly also total # of elements [row col] = size(mat); if nargout == 3 varargout{1} = row*col; end end § 세번째 출력인자를 요구하는 경우 “전체 elem의 개수”를 출력 >> [r c] = mysize(eye(3)) r = 3 c = 3 >> [r c elem] = mysize(eye(3)) r = 3 c = 3 elem = 9 § 세번째 출력인자를 요구하는 경우 “전체 elem의 개수”를 출력 § Eye(3)= 1 1 1
  • 65. GIST 정보통신공학과 Winter School 2015, 강재욱 Warping up – Day 2 1. Vectorized Code 4. Logical Vectors 5. Vectorizing Code 2. Advanced MATLAB Functions 1. Anonymous Functions 2. Uses of Function Handles 3. Variable Number of Arguments 65