Download - MATLAB 프로그래밍
1
MATLAB MATLAB 프로그래밍프로그래밍
2
MATLABMATLAB
MATLAB 이란 ?mathworks 사 (http://www.mathworks.com) 개발수치해석 및 프로그래밍 환경을 제공하는 공학용 툴
특징행렬 처리 용이함수와 데이터의 그래프 표현사용자 인터페이스 생성 및 다른 프로그래밍 언어 연결 가능다양한 내장 함수 및 툴박스 제공플랫폼 독립적
3
MATLAB MATLAB 데스크탑데스크탑
4
MATLAB MATLAB 스칼라스칼라
값 배정
소수점이하 15 자리까지 표현
소수점이하 4 자리까지 표현
5
MATLAB MATLAB 벡터벡터 , , 행렬행렬
행 벡터a = [ 1 2 3 4 5 ]
열 벡터b = [ 2 ; 4 ; 6 ; 8 ; 10 ]
b = [ 2 4 6 8 10 ] ‘ ‘ : 전치행렬
b(4) 인덱스번호는 1 부터 시작 , 8 출력
행렬c = [ 1 2 3 ; 4 5 6 ; 7 8 9 ]
c(2,3) ( 행번호 , 열번호 ) 6 출력
6
MATLAB MATLAB 벡터벡터 , , 행렬행렬
콜론 (:) 연산자
1 부터 5 까지 1 씩 증가하는 행벡터
1 부터 3 까지 0.5 씩 증가하는 행벡터
인덱스 2~4 까지의 벡터 추출
7
MATLAB MATLAB 벡터벡터 , , 행렬행렬
콜론 (:) 연산자
2 행 , 인덱스 생략
3 행 , 1 열과 2 열
2~3 행 , 1~2 열로 구성된 2x2 행렬 반환
8
MATLAB MATLAB 벡터벡터 , , 행렬행렬
linspace(x1, x2, n)x1 과 x2 사이의 등 간격 n 개의 포인트 생성
logspace(x1, x2, n)10x1 과 10x2 사이에 지수적 등 간격 n 개의 포인트 생성
9
MATLAB MATLAB 벡터벡터 , , 행렬행렬
eye(n)nxn 단위행렬 (identity matrix)
zeros(n,m)nxm 0 행렬
ones(n,m)mxm 행렬 ( 모든 원소의 값이 1)
…
10
수학 연산수학 연산
우선순위 연산자 설명1 ^ 지수 계산2 - 음부호3 * / 곱셈 , 나눗셈4 \ 왼쪽 나눗셈 ( 행렬 연산 )
5 + - 덧셈 , 뺄셈
>> y = pi / 4>> -y^2.45>> (-y)^2.45
11
행렬 연산행렬 연산
OperationMATLAB Form
Comments
Array Addition a + bArray addition and matrix addition are identical
Array Subtraction a – bArray subtraction and matrix subtraction are identical
Array Multiplication a . * bElement-by-element multiplication of a and b. Both arrays must be the same shape, or one of them must be a scalar
Matrix Multiplication a * bMatrix multiplication of a and b. The number of columns in a must equal the number of rows in b.
Array Right Division a ./ b
Element-by-element division of a and b : a(i,j) / b(i,j). Both arrays must be the same shape, or one of them must be a scalar.
Array Exponentiation a. ^ b
Element-by-element exponentiation of a and b : a(i,j) ^ b(i,j). Both arrays must be the same shape, or one of them must be a scalar
12
행렬 연산 예제행렬 연산 예제
덧셈 /뺄셈a = [ 1 2 3 4 5 ]; b = [ 2 4 6 8 10];c = a + b
곱셈a = [ 1 2 3 4 5 ]; b = [ 2 4 6 8 10 ]’c = 2 * aa*b
외적 (outer product)b * a
13
행렬 연산 예제행렬 연산 예제
지수정방행렬 ^ 지수승
배열 연산자 (. 연산자 )각 원소끼리 연산.*
./
.^
14
내장 함수내장 함수
Trigonometric Functions
Function Description
cos(x) Calculates cos x, with x in radians.
acos(x) Calculates cos-1x, with the results in radians.
sin(x) Calculates sin x, with x in radians.
asin(x) Calculates sin-1x, with the results in radians.
tan(x) Calculates tan x, with x in radians.
atan(x) Calculates tan -1x, with the results in radians.
mod(x,y) Remainder, or modulo, function.
sqrt(x) Calculates the square root of x.
>> sqrt(2)
ans =
1.4142
15
내장 함수내장 함수
Round, Exponential, Logarithm
Function Description
[value,index] = max(x)
Returns the maximum value in vector x, and optionally the location of that value.
[value,index] = min(x)
Returns the minimum value in vector x, and optionally the location of that value.
ceil(x) Rounds x to the nearest integer towards positive infinity :ceil ( 3.1 ) = 4 and ceil ( -3.1 ) = -3
fix(x) Rounds x to the nearest integer towards zero :fix ( 3.1 ) = 3 and fix ( -3.1 )= -3
floor(x) Rounds x to the nearest integer towards minus infinity :floor ( 3.1 ) = 3 and floor ( -3.1 ) = -4
round(x) Rounds x to the nearest integer
exp(x) Calculates ex.
log(x) Calculates the natural logarithm log e x.
log2(x) Calculates the natural logarithm log 2 x.
16
내장 함수내장 함수
Complex & Rational Numbers
Helphelp 함수명
Function Description
abs(x) Calculates |x|.
angle(x) Returns the phase angle of the complex value x, in radians
conj(z) Calculates conjugate of z.
imag(z) Calculates imaginary part of z.
real(z) Calculates real part of of z.
rat(x) Calculates rational approximation of x
rats(x) Calculates rational output of x
17
함수 활용 예함수 활용 예
자유낙하 속도 측정
t=[0:2:20]’;
g=9.81; m=68.1; cd=0.25;
v=sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t)
t
m
gc
c
gmv d
d
tanh
v : 속도 (m/s)g : 중력가속도 (9.81m/s2)m : 질량 (kg)cd : 항력계수 (kg/m)
t : 시간 (s)
v = 0 18.7292 33.1118 42.0762 46.9575 49.4214 50.6175 51.1871 51.4560 51.5823 51.6416
18
그래픽 표현그래픽 표현
Figureplotstemstairsbarcompasspiesemilogsemilogxsemilogy
plot
stairs
compass
stem
bar
pie
19
그래픽 표현그래픽 표현
Labelxlabel (‘x_string’)ylabel (‘y_string’)
Titletitle (‘string’)
LegendLegends can be created with the legend function.The basic form of this function is
legend(‘string1’, ’string2’, . . . , pos)
pos 설명 pos 설명
0Automatic “best” placement (least conflict with data)
1 Upper right-hand corner (default)
2 Upper left-hand corner 3 Lower left-hand corner
4 Lower right-hand corner -1 To the right of the plot
20
그래픽 표현그래픽 표현
Colors & StylesColor Marker Style Line Style
y yellow . point - solid
m magenta o circle : dotted
c cyan x x-mark -. dash-dot
r red + plus -- dashed
g green * star <none> no line
b blue s square
w white d diamond
k black v triangle (down)
^ triangle (up)
< triangle (left)
> triangle (right)
p pentagram
h hexagram
<none> no marker
21
그래픽 표현그래픽 표현x=0:pi/100:2*pi;
y1=sin(2*x);
y2=2*cos(2*x);
plot(x,y1,'k-o',x,y2,'b--v')
title('Plot of f(x)=sin(2x) and its derivative')
xlabel('x')
ylabel('y')
legend('f(x)','d/dx f(x)',4)
grid on
22
그래픽 표현그래픽 표현
사랑의 방정식
225171617 22 yyxx
x=[-4.15:0.001:4.15];a=17;b=-16*abs(x);c=17*x.^2 - 225;y1=(-b+sqrt(b.^2 - 4*a.*c))/(2*a);y2=(-b-sqrt(b.^2 - 4*a.*c))/(2*a); plot(x,real(y1))hold onplot(x,real(y2))grid on
23
스크립트 파일스크립트 파일
M- 파일 작성 scriptdemo.m
g=9.81; m=68.1; t=12; cd=0.25;
v=sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t)
>> scriptdemo
24
함수 파일함수 파일
함수 형식
예제 ) freefallvel.m function velocity = freefallvel(m,cd,t)
% 자유낙하 속도 계산 % 입력 ) m: 질량 (kg), cd: 항력계수 , t: 시간 ( 초 )
% 출력 ) t 초 후 낙하 속도 출력 g = 9.81;
velocity=sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t);
>> freefallvel(68.1, 0.25, 12)
function outvar = funcname(arglist)
% help comments
statements
outvar = value
25
여러 개의 값 반환여러 개의 값 반환
stats.m function [ mean, stdev ] = stats (x)
n = length(x);
mean = sum(x) / n;
stdev = sqrt ( sum((x-mean).^2 / (n-1)));
>> y = [ 8 5 10 12 6 7.5 4 ]
>> [ m , s ] = stats(y)
m = 7.5000
s = 2.8137
26
input input 함수함수
형식 n = input(‘prompt string’)
설명 명령창에 ‘prompt string’ 을 출력하고 값을 입력 받음
예제m = input(‘Mass (kg): ’)
>> Mass (kg): 68.1_
name = input(‘Enter your name: ’,‘s’)
% 문자열 입력 >> enter your name: Matlab_
27
disp disp 함수함수
형식disp( value )
설명명령창에 value 값 출력
예제
28
fprintf fprintf 함수함수
형식 fprintf( ‘ format ’, arglist … )
설명 주어진 format 에 맞춰 값을 출력
포맷 / 제어 코드
코드 설명
%d 정수 포맷
%e e 를 사용하는 과학 포맷
%E E 를 사용하는 과학 포맷
%f 소수 포맷
%g %e 나 %f 중에서 간단한 포맷
\n 새로운 줄로 시작
\t 탭
29
fprintf fprintf 예제예제
fprintfdemo.m function fprintfdemo x = [ 1 2 3 4 5 ];
y = [ 20.4 12.6 17.8 88.7 120.4 ];
z = [ x ; y ];
fprintf(‘ x y \n’);
fprintf(‘ %5d %10.3f \n’, z);
결과1 20.400
2 12.600
3 17.800
……
30
대화식 대화식 M-M- 파일 작성파일 작성
freefallinteract.mfunction velocity = freefallinteract
% freefallinteract() : 자유낙하 속도 계산g = 9.81;
m = input( ‘ 무게 (kg) : ’);
cd = input( ‘ 항력계수 (kg/m) : ’);
t = input( ‘ 시간 (s) : ’);
disp( ‘ 낙하속도 (m/s) : ’ )disp( sqrt(g*m/cd)*tanh(sqrt(g*cd/m)* t) )
실행>> freefallinteract
무게 (kg) : 68.1
항력계수 (kg/m) : 0.25
시간 (s) : 12
낙하속도 (m/s) : 50.6175
31
함수호출함수호출
freefallinteract.m 수정function velocity = freefallinteract
% freefallinteract() : 자유낙하 속도 계산m = input( ‘ 무게 (kg) : ’);
cd = input( ‘ 항력계수 (kg/m) : ’);
t = input( ‘ 시간 (s) : ’);
disp( ‘ 낙하속도 (m/s) : ’ )disp( freefallvel(m,cd,t) )
freefallvel.m 의 freefallvel 함수를 호출
32
관계관계 //논리 연산논리 연산
관계연산자
논리 연산자
x == 0 == Equal
unit ~= ‘m’ ~= Not equal
a < 0 < Less than
s > t > Greater than
3.9 <= a / 3 <= Less than or equal to
r >= 0 >= Greater than or equal to
~x ~ Not
x & y & And
x | y | Or
33
판정 판정 : if : if 구문구문
형식 if condition
statements end
설명 condition 이 참 (1) 이면 statements 수행 거짓 (0) 이면 수행 안함
예제 if grade >= 60
disp( ‘ passing grade: ’ ) disp( grade ); end if grade >= 60, disp( ‘ passing grade: ’ ), end
34
에러함수 에러함수 : error: error
형식 error( msg )
설명 텍스트 메시지 msg 를 출력하고 m- 파일 종료
예제 if x == 0, error(‘Zero value encountered’), end f = 1 / x;
35
if / else if / else 구문구문
mysign.m function sgn = mysign (x)
% mysign(x) : return 1 if x is greater then zero
% -1 if x is less then zero % 0 if x is equal to zero
if x > 0 sgn = 1;
elseif x < 0 sgn = -1;
else sgn = 0; end
36
for for 구문구문
형식 for index = start : step : finish
statements
end
설명 index 값을 start 부터 finish 까지 step 씩 증가 /감소 시키면서 statements 를 반복 실행
예제 i = 0; for t = 0:0.02:50 i = i + 1;
y(i) = cos(t)end
t = 0:0.02:50;y = 5 * cos(t)
37
메모리 사전 할당메모리 사전 할당
t = 0:0.01:5;for i = 1:length(t)
if t(i) > 1 y(i) = 1 / t(i);else y(i) = 1;end
end
t = 0:0.01:5;y = ones( size(t) );for i = 1:length(t) if t(i) > 1
y(i) = 1 / t(i); endend
배열의 크기가 예측 가능하면미리 메모리를 할당
38
while while 구조구조
형식 while condition
statements
end
설명 condition 이 참 (1) 인 동안 statements 를 반복 수행
예제 while x > 0 while(1)
x = x – 3; if x < 0, break, end
disp( x ) x = x – 5;
end end
39
Gauss EliminationGauss Elimination
function [ x ] = GaussNaive( A, b )
% GaussNaive(A,b) :
% Gauss elimination without pivoting
% input:
% A = coefficient matrix
% b = right hand side vector
% output:
% x = solution vector
[m,n] = size(A);
if m~=n, error('Matrix A must be square'); end
nb = n+1;
Aug = [A b];
40
Gauss EliminationGauss Elimination
% forward elimination
for k = 1:n-1
for i = k+1:n
factor = Aug(i,k)/Aug(k,k);
Aug(i,k:nb) = Aug(i,k:nb)-factor*Aug(k,k:nb);
end
end
% back substitution
x = zeros(n,1);
x(n) = Aug(n,nb)/Aug(n,n);
for i = n-1:-1:1
x(i) = (Aug(i,nb)-Aug(i,i+1:n)*x(i+1:n))/Aug(i,i);
end
41
Gauss EliminationGauss Elimination
실행결과
x1 + x2 + 2x3 = 9
2x1 + 4x2 – 3x3 = 1
3x1 + 6x2 – 5x3 = 0
>> A = [ 1 1 2 ; 2 4 -3 ; 3 6 -5 ];
>> b = [ 9 1 0 ]’;
>> GaussNaive(A,b)
ans =
1
2
3
42
HomeworkHomework
Gauss-Jordan EliminationMake a MATLAB program ‘GaussJordan.m’ runs as follows
>> A = [ 1 1 2 ; 2 4 -3 ; 3 6 -5 ];
>> b = [ 9 1 0 ]’;
>> GaussJordan(A,b)
ans =
1 0 0 1
0 1 0 2
0 0 1 3
Refer two samples: GaussNaive.m, GaussianElimination.mReference for MATLAB syntax: Matlab.pdf