강의노트

Download Report

Transcript 강의노트

MATLAB 프로그래밍
1
MATLAB
MATLAB이란?
mathworks 사(http://www.mathworks.com) 개발
수치해석 및 프로그래밍 환경을 제공하는 공학용 툴
특징
행렬 처리 용이
함수와 데이터의 그래프 표현
사용자 인터페이스 생성 및 다른 프로그래밍 언어 연결 가능
다양한 내장 함수 및 툴박스 제공
플랫폼 독립적
2
MATLAB 데스크탑
3
MATLAB 스칼라
값 배정
소수점이하 15자리까지 표현
소수점이하 4자리까지 표현
4
MATLAB 벡터, 행렬
행 벡터
a=[1 2 3 4 5]
열 벡터
b = [ 2 ; 4 ; 6 ; 8 ; 10 ]
b = [ 2 4 6 8 10 ] ‘
b(4)
‘ : 전치행렬
인덱스번호는 1부터 시작, 8출력
행렬
c=[123;456;789]
c(2,3)
(행번호, 열번호) 6출력
5
MATLAB 벡터, 행렬
콜론(:) 연산자
1부터 5까지 1씩 증가하는 행벡터
1부터 3까지 0.5씩 증가하는 행벡터
인덱스 2~4까지의 벡터 추출
6
MATLAB 벡터, 행렬
콜론(:) 연산자
2행, 인덱스 생략
3행, 1열과 2열
2~3행, 1~2열로 구성된 2x2 행렬 반환
7
MATLAB 벡터, 행렬
linspace(x1, x2, n)
x1과 x2 사이의 등 간격 n개의 포인트 생성
logspace(x1, x2, n)
10x1과 10x2 사이에 지수적 등 간격 n개의 포인트 생성
8
MATLAB 벡터, 행렬
eye(n)
nxn 단위행렬(identity matrix)
zeros(n,m)
nxm 0행렬
ones(n,m)
mxm 행렬(모든 원소의 값이 1)
…
9
수학 연산
우선순위
연산자
설명
1
^
지수 계산
2
-
음부호
3
4
* /
\
곱셈, 나눗셈
5
+-
덧셈, 뺄셈
왼쪽 나눗셈(행렬 연산)
>> y = pi / 4
>> -y^2.45
>> (-y)^2.45
10
행렬 연산
Operation
MATLAB Form
Comments
Array Addition
a+b
Array addition and matrix addition are
identical
Array Subtraction
a–b
Array subtraction and matrix subtraction are
identical
a.*b
Element-by-element multiplication of a and b.
Both arrays must be the same shape, or one
of them must be a scalar
a*b
Matrix multiplication of a and b. The number
of columns in a must equal the number of
rows in b.
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.
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
Array Multiplication
Matrix Multiplication
Array Right Division
Array Exponentiation
11
행렬 연산 예제
덧셈/뺄셈
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*a
a*b
외적(outer product)
b*a
12
행렬 연산 예제
지수
정방행렬 ^지수승
배열 연산자(.연산자)
각 원소끼리 연산
.*
./
.^
13
내장 함수
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
mod(x,y)
Remainder, or modulo, function.
sqrt(x)
Calculates the square root of x.
>> sqrt(2)
ans =
1.4142
-1x,
with the results in radians.
14
내장 함수
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 e-x.
log(x)
Calculates the natural logarithm log e x.
log2(x)
Calculates the natural logarithm log 2 x.
15
내장 함수
Complex & Rational Numbers
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
Help
help 함수명
16
함수 활용 예
자유낙하 속도 측정
v
 gcd 
gm
tanh 
t 
cd
 m 
v : 속도(m/s)
g : 중력가속도(9.81m/s2)
m : 질량(kg)
cd : 항력계수(kg/m)
t : 시간(s)
v=
t=[0:2:20]’;
g=9.81; m=68.1; cd=0.25;
v=sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t)
0
18.7292
33.1118
42.0762
46.9575
49.4214
50.6175
51.1871
51.4560
51.5823
51.6416
17
그래픽 표현
Figure
plot
stem
stairs
bar
compass
pie
semilog
semilogx
semilogy
plot
stem
stairs
bar
compass
pie
18
그래픽 표현
Label
xlabel (‘x_string’)
ylabel (‘y_string’)
Title
title (‘string’)
Legend
Legends can be created with the legend function.
The basic form of this function is
 legend(‘string1’, ’string2’, . . . , pos)
pos
설명
pos
설명
0
Automatic “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
19
그래픽 표현
Colors & Styles
Color
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
20
그래픽 표현
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
21
그래픽 표현
사랑의 방정식
17 x 2  16 x y  17 y 2  225
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 on
plot(x,real(y2))
grid on
22
스크립트 파일
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
23
함수 파일
함수 형식
function outvar = funcname(arglist)
% help comments
statements
outvar = value
예제) 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)
24
여러 개의 값 반환
stats.m
function [ mean, stdev ] = stats (x)
n = length(x);
mean = sum(x) / n;
stdev = sqrt ( sum((x-mean).^2 / (n-1)));
>> y =
>> [ m
m =
s =
[ 8 5 10 12 6 7.5 4 ]
, s ] = stats(y)
7.5000
2.8137
25
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_
26
disp 함수
형식
disp( value )
설명
명령창에 value 값 출력
예제
27
fprintf 함수
형식
fprintf( ‘ format ’, arglist … )
설명
주어진 format에 맞춰 값을 출력
포맷 / 제어 코드
코드
설명
%d
정수 포맷
%e
e를 사용하는 과학 포맷
%E
E를 사용하는 과학 포맷
%f
소수 포맷
%g
%e나 %f 중에서 간단한 포맷
\n
새로운 줄로 시작
\t
탭
28
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
2
3
20.400
12.600
17.800
……
29
대화식 M-파일 작성
freefallinteract.m
function 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
30
함수호출
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함수를 호출
31
관계/논리 연산
관계연산자
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
32
판정 : 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
33
에러함수 : error
형식
error( msg )
설명
텍스트 메시지 msg를 출력하고 m-파일 종료
예제
if x == 0, error(‘Zero value encountered’), end
f = 1 / x;
34
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
35
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)
36
메모리 사전 할당
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);
end
end
배열의 크기가 예측 가능하면
미리 메모리를 할당
37
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
38
Gauss 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];
39
Gauss 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
40
Gauss 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
41
Homework
Gauss-Jordan Elimination
Make 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.m
Reference for MATLAB syntax: Matlab.pdf
42