You are on page 1of 28

1.

MATLAB 일반

이번 강의에서는 Matlab을 어떻게 사용하는지에 대해 배우기로 한다. 목표로는 다음과 같은


작업들을 할 수 있어야 하겠다.
1. help기능과, 기본연산 뿐 아니라 기본적인 수학적 함수를 사용할 줄 알아야 한다.
2. 행렬에 대한 사칙연산을 할 수 있어야 한다.
3. polynomial fitting을 할 수 있어야 한다.
4. 그래프를 원하는 대로 그릴 수 있어야 한다.
5. m파일을 활용하여 복잡한 알고리듬을 작성할 수 있어야 한다 (즉, if문, for문, file
입출력, subroutine작성 등을 활용).
6. ordinary differential equation을 쉽게 풀 수 있어야 한다.
Matlab에는 위에서 언급한 기능 외에도 다양한 기능들이 toolbox내에 제공된다. 위의 작업들은
일부 내장 함수들의 활용법에 대한 간단한 사례일 뿐이다. Matlab을 100% 활용하기 위해서는
매뉴얼을 보고 원하는 기능을 찾아서 코딩할 수 있어야 한다.

1.1 Help및 기본 연산자

- 사칙연산 : +,-,*,/
예) 먼저 MATLAB을 실행하면 MATLAB Command Window가 뜬다. 그리고 다음을
타이핑 하고 리턴을 치면 다음과 같은 결과를 얻는다. 나머지 연산도 연습을 해보자.
>>1.5+3.5
ans =
5

- help를 사용하는 방법은 다음과 같다. +에 대한 help를 보고 싶으면 help +를 치고


리턴을 치면 아래와 같은 도움말이 나온다.

>> help +
Operators and special characters.
Arithmetic operators.
plus - Plus +
uplus - Unary plus +
minus - Minus -
uminus - Unary minus -
mtimes - Matrix multiply *

1
times - Array multiply .*
mpower - Matrix power ^
power - Array power .^
mldivide - Backslash or left matrix divide \
mrdivide - Slash or right matrix divide /
ldivide - Left array divide .\
rdivide - Right array divide ./
kron - Kronecker tensor product kron
Relational operators.
eq - Equal ==
ne - Not equal ~=
lt - Less than <
gt - Greater than >
le - Less than or equal <=
ge - Greater than or equal >=
Logical operators.
Short-circuit logical AND &&
Short-circuit logical OR ||
and - Element-wise logical AND &
or - Element-wise logical OR |
not - Logical NOT ~
xor - Logical EXCLUSIVE OR
any - True if any element of vector is nonzero
all - True if all elements of vector are nonzero

- 웹사이트 www.mathworks.com에서 다양한 도움을 받을 수 있다. 이 사이트에는 다양한


예제와 함수들의 기능에 대한 설명이 나와 있다.

- 변수 이용 : 다음과 같이 어떤 변수에 값을 저장 할 수도 있고 변수끼리 연산을 할 수도


있다.
>>a=1.5
a=
1.5000
>>b=3.5
b=
3.5000

2
>>a+b
ans =
5

- 화면 상에 결과를 보여줄 것인지 안보여줄 것인지는 세미콜론(;)을 연산식 뒤에 붙이느냐


안 붙이느냐에 달려 있다. 즉 ;을 붙이면 결과가 보이지 않는다.

;을 붙이지 않았을 때
>>c=1.0
c=
1
;을 붙였을 때
>>c=1.0;
>>

- 다양한 수학 함수 (exp, log, log10, sin, asin (역사인함수), cos, acos, tan, atan, atan2,
^ (승), sind, asind, cosd, tand, abs 등)
>> 5.0^3
ans =
125
>>exp(5)
ans =
148.4132

1.2 행렬 지정과 행렬 연산
- 행벡터 지정과 값 불러오기
>>A=[1 2 3 4 5]
A=
1 2 3 4 5
>>A(3)
ans =
3
>>A(5)
ans =
5

3
- 열벡터 지정
>> B=[1; 2; 3; 4; 5]
B=
1
2
3
4
5

- 행렬 지정과 값 불러오기
>>C=[1 2 3 ; 4 5 6]
C=
1 2 3
4 5 6
>>C(2,3)
ans =
6

- 행렬의 transpose
>> D=[1 3 5 6 ; 6 3 0 -3]
D=
1 3 5 6
6 3 0 -3
>>E=D'
E=
1 6
3 3
5 0
6 -3

- 행렬의 더하기(+)
>> A=[1 2 3 ; 6 3 0 ]
A=
1 2 3
6 3 0
>> B=[ 0 2 1 ; 9 5 1]

4
B=
0 2 1
9 5 1
>>C=A+B
C=
1 4 4
15 8 1

- 행렬 곱하기 (*)
>>A=[1 2 3 ; 6 3 0 ]
A=
1 2 3
6 3 0
>>B=[-1 -3 ; -6 -8; -1 -2]
B=
-1 -3
-6 -8
-1 -2
>>C=A*B
C=
-16 -25
-24 -42

- 역 행렬 구하기 (inv)
>> A=[1 2 3; 8 4 0; -6 -5 -3]
A=
1 2 3
8 4 0
-6 -5 -3
>> C=inv(A)
C=
1.0000 0.7500 1.0000
-2.0000 -1.2500 -2.0000
1.3333 0.5833 1.0000

- rank, eye, ^, : , length, min, max, eig, svd, cond 등을 연습해보자.

5
1.3 그래프
- 그래프를 그리는데 plot이라는 명령을 사용할 것이다. 먼저 다음과 같이 도움말의
도움을 받아 보자.

>> help plot


PLOT Linear plot.
PLOT(X,Y) plots vector Y versus vector X. If X or Y is a matrix,
then the vector is plotted versus the rows or columns of the matrix,
whichever line up. If X is a scalar and Y is a vector, length(Y)
disconnected points are plotted.

PLOT(Y) plots the columns of Y versus their index.


If Y is complex, PLOT(Y) is equivalent to PLOT(real(Y),imag(Y)).
In all other uses of PLOT, the imaginary part is ignored.

Various line types, plot symbols and colors may be obtained with
PLOT(X,Y,S) where S is a character string made from one element
from any or all the following 3 columns:
b blue . point - solid
g green o circle : dotted
r red x x-mark -. dashdot
c cyan + plus -- dashed
m magenta * star (none) no line
y yellow s square
k black d diamond
v triangle (down)
^ triangle (up)
< triangle (left)
> triangle (right)
p pentagram
h hexagram
For example, PLOT(X,Y,'c+:') plots a cyan dotted line with a plus
at each data point; PLOT(X,Y,'bd') plots blue diamond at each data
point but does not draw any line.

6
PLOT(X1,Y1,S1,X2,Y2,S2,X3,Y3,S3,...) combines the plots defined by
the (X,Y,S) triples, where the X's and Y's are vectors or matrices
and the S's are strings.

For example, PLOT(X,Y,'y-',X,Y,'go') plots the data twice, with a


solid yellow line interpolating green circles at the data points.

See also plottools, semilogx, semilogy, loglog, plotyy, plot3, grid,


title, xlabel, ylabel, axis, axes, hold, legend, subplot, scatter.

- x,y 데이터를 plot함수를 사용하여 그래프로 그려보자. 결과는 그림과 같게 나온다.


>> x=[1 2 3 4 5 6 7 8 9 10];
>> y=[0 5 8 10 11 11 10 8 5 0];
>> plot(x,y)
>>

12

10

0
1 2 3 4 5 6 7 8 9 10

- 그림에서  Edit메뉴  Axis Properties 를 선택하고 축을 클릭해서 축에 이름을 붙여


보자. 혹은 바로 축을 더블 클릭해도 같은 작업을 할 수 있다.

7
12

10

6
y

0
1 2 3 4 5 6 7 8 9 10
x

- 그림에서 라인을 더블 클릭 해서 라인의 형태나 값을 바꾸어 보자.

12

10

6
y

0
1 2 3 4 5 6 7 8 9 10
x

- 그림에서  Insert메뉴  Legend를 선택하여 Legend를 넣어보자.

8
12
process output

10

6
y

0
1 2 3 4 5 6 7 8 9 10
x

- 그림에서  Edit메뉴  Copy Figure를 해서 Word로 옮겨 복사를 해보자. 위의


그림들은 모두 이 Copy기능을 이용하여 붙인 것이다.

- 그림에서 +돋보기와 –돋보기를 이용하여 그림의 일정 부분을 확대를 하기도 하고


축소를 하기도 해보자.

11 °øÁ¤ µ¥ÀÌŸ

10.5

10
y

9.5

8.5

8
2 3 4 5 6 7 8 9
x

- 지금까지의 그래프를 다음의 command를 이용하여 그려보자. 결과는 그림과 같게 나온다.

9
>> x=[1 2 3 4 5 6 7 8 9 10];
>> y=[0 5 8 10 11 11 10 8 5 0];
>> plot(x,y,'k-+','LineWidth',2)
>> xlabel('x')
>> ylabel('y')
>> legend('process data')
>> title('test graph')
>> axis([0 11 -1 12])
>>

test graph
12
process data

10

6
y

0 1 2 3 4 5 6 7 8 9 10 11
x

- 3차원 그래프를 그려보자. 먼저 plot3에 대해 알아 보자. Plot과는 달리 삼차원에서 선을


그려준다.
>> help plot3
PLOT3 Plot lines and points in 3-D space.
PLOT3() is a three-dimensional analogue of PLOT().

PLOT3(x,y,z), where x, y and z are three vectors of the same length,


plots a line in 3-space through the points whose coordinates are the
elements of x, y and z.

10
PLOT3(X,Y,Z), where X, Y and Z are three matrices of the same size,
plots several lines obtained from the columns of X, Y and Z.

Various line types, plot symbols and colors may be obtained with
PLOT3(X,Y,Z,s) where s is a 1, 2 or 3 character string made from
the characters listed under the PLOT command.

PLOT3(x1,y1,z1,s1,x2,y2,z2,s2,x3,y3,z3,s3,...) combines the plots


defined by the (x,y,z,s) fourtuples, where the x's, y's and z's are
vectors or matrices and the s's are strings.

Example: A helix:

t = 0:pi/50:10*pi;
plot3(sin(t),cos(t),t);

PLOT3 returns a column vector of handles to lineseries objects, one


handle per line. The X,Y,Z triples, or X,Y,Z,S quads, can be
followed by parameter/value pairs to specify additional
properties of the lines.

See also plot, line, axis, view, mesh, surf.

- plot3을 이용하여 3차원 선을 다음과 같이 그려보자.


>> x=[-5 -4 -3 -2 -1 0 1 2 3 4 5];
>> y=[-5 -4 -3 -2 -1 0 1 2 3 4 5];
>> for j=1:11
z(j)=x(j)^3-y(j)^3-10*x(j)*y(j);
end
>> plot3(x,y,z)
>> grid on

11
0

-50

-100

-150

-200

-250
5
5
0
0

-5 -5

- 다음으로 mesh 함수에 대해 알아 보자. 이것은 plot3와는 달리 선이 아니라 면을 그려준다.


>> help mesh
MESH 3-D mesh surface.
MESH(X,Y,Z,C) plots the colored parametric mesh defined by
four matrix arguments. The view point is specified by VIEW.
The axis labels are determined by the range of X, Y and Z,
or by the current setting of AXIS. The color scaling is determined
by the range of C, or by the current setting of CAXIS. The scaled
color values are used as indices into the current COLORMAP.

MESH(X,Y,Z) uses C = Z, so color is proportional to mesh height.

MESH(x,y,Z) and MESH(x,y,Z,C), with two vector arguments replacing


the first two matrix arguments, must have length(x) = n and
length(y) = m where [m,n] = size(Z). In this case, the vertices
of the mesh lines are the triples (x(j), y(i), Z(i,j)).
Note that x corresponds to the columns of Z and y corresponds to
the rows.

MESH(Z) and MESH(Z,C) use x = 1:n and y = 1:m. In this case,


the height, Z, is a single-valued function, defined over a

12
geometrically rectangular grid.

MESH(...,'PropertyName',PropertyValue,...) sets the value of


the specified surface property. Multiple property values can be set
with a single statement.

MESH returns a handle to a surface plot object.

See also surf, meshc, meshz, waterfall.

- mesh함수를 이용하여 다음의 데이터에 대한 3차원 그래프를 그려보자.


>> x=[-5 -4 -3 -2 -1 0 1 2 3 4 5];
>> y=[-5 -4 -3 -2 -1 0 1 2 3 4 5];
>> for i=1:11
for j=1:11
z(i,j)=x(i)^2+y(j)^2;
end
end
>> mesh(x,y,z)
>> xlabel('x')
>> ylabel('y')
>> zlabel('z')
>> title('test 3D graph')
>>

test 3D graph

50

40

30
z

20

10

0
5
5
0
0

y -5 -5
x

- view함수를 이용하여 다양한 각도에서 보는 그래프를 그려보자.

13
>> view([0,20])
>> view([10,20])
>> view([20,20])
>> view([30,20])
>> view([40,20])
>> view([40,30])
>> view([40,40])
>> view([40,50])
test 3D graph

60

40
z

20

0 5
-5

0
0

5 -5 y
x

- mesh에서 사용했던 데이터에 대해 이번에는 surf 함수를 이용하여 3D 그래프를 그려보자.


>> help surf
SURF 3-D colored surface.
SURF(X,Y,Z,C) plots the colored parametric surface defined by
four matrix arguments. The view point is specified by VIEW.
The axis labels are determined by the range of X, Y and Z,
or by the current setting of AXIS. The color scaling is determined
by the range of C, or by the current setting of CAXIS. The scaled
color values are used as indices into the current COLORMAP.
The shading model is set by SHADING.

SURF(X,Y,Z) uses C = Z, so color is proportional to surface height.

SURF(x,y,Z) and SURF(x,y,Z,C), with two vector arguments replacing


the first two matrix arguments, must have length(x) = n and
length(y) = m where [m,n] = size(Z). In this case, the vertices
of the surface patches are the triples (x(j), y(i), Z(i,j)).
Note that x corresponds to the columns of Z and y corresponds to
the rows.

SURF(Z) and SURF(Z,C) use x = 1:n and y = 1:m. In this case,


the height, Z, is a single-valued function, defined over a
geometrically rectangular grid.

SURF(...,'PropertyName',PropertyValue,...) sets the value of the


specified surface property. Multiple property values can be set
with a single statement.

SURF(AX,...) plots into AX instead of GCA.

14
SURF returns a handle to a surface plot object.

AXIS, CAXIS, COLORMAP, HOLD, SHADING and VIEW set figure, axes, and
surface properties which affect the display of the surface.

See also surfc, surfl, mesh, shading.

>> surf(x,y,z)
>> view([40,40])
>> colorbar
>>

45

40

50 35

40
30
30
25
20
20
10
15
0 5
-5 10

0 5
0

5 -5

- contour 함수를 이용하여 등고선 그래프를 그려보자.


>> help contour
CONTOUR Contour plot.
CONTOUR(Z) is a contour plot of matrix Z treating the values in Z
as heights above a plane. A contour plot are the level curves
of Z for some values V. The values V are chosen automatically.
CONTOUR(X,Y,Z) X and Y specify the (x,y) coordinates of the
surface as for SURF.
CONTOUR(Z,N) and CONTOUR(X,Y,Z,N) draw N contour lines,
overriding the automatic value.
CONTOUR(Z,V) and CONTOUR(X,Y,Z,V) draw LENGTH(V) contour lines
at the values specified in vector V. Use CONTOUR(Z,[v v]) or
CONTOUR(X,Y,Z,[v v]) to compute a single contour at the level v.
CONTOUR(AX,...) plots into AX instead of GCA.
[C,H] = CONTOUR(...) returns contour matrix C as described in
CONTOURC and a handle H to a contourgroup object. This handle can
be used as input to CLABEL.

The contours are normally colored based on the current colormap


and are drawn as PATCH objects. You can override this behavior
with the syntax CONTOUR(...,LINESPEC) to draw the contours
with the color and linetype specified. See the help for PLOT
for more information about LINESPEC values.

The above inputs to CONTOUR can be followed by property/value

15
pairs to specify additional properties of the contour object.

Uses code by R. Pawlowicz to handle parametric surfaces and


inline contour labels.

Example:
[c,h] = contour(peaks); clabel(c,h), colorbar

See also contour3, contourf, clabel, colorbar.

>> x=[-5 -4 -3 -2 -1 0 1 2 3 4 5];


y=[-5 -4 -3 -2 -1 0 1 2 3 4 5];
for i=1:11
for j=1:11
z(i,j)=x(i)^2+y(j)^2;
end
end
>>
>> contour(x,y,z)
>> colorbar

4 45

3 40

2
35
1
30
0
25
-1
20
-2

-3 15

-4 10

-5
-5 0 5

>> [c,h]=contour(x,y,z);
>> clabel(c,h)

16
5 30 25 30 45
45 40
40 20 25
4 35
15

35
25 20 15 20
3 10

2 5

10

25
15
25
20
1

15
10
5
10
0

20
-1

-2 5
15

10

25
10 15
25

20

-3

35 15 20
-4 35
40 20
45 30 25 25
30 40 45
-5
-5 -4 -3 -2 -1 0 1 2 3 4 5

1.4 Polynomial Fitting


- 실험 데이터가 주어졌을 때 polyfit함수를 이용하여 polynomial식을 구해 보자.
>> help polyfit
POLYFIT Fit polynomial to data.
POLYFIT(X,Y,N) finds the coefficients of a polynomial P(X) of
degree N that fits the data, P(X(I))~=Y(I), in a least-squares sense.

[P,S] = POLYFIT(X,Y,N) returns the polynomial coefficients P and a


structure S for use with POLYVAL to obtain error estimates on predictions.
P is a row vector of length N+1 containing the polynomial coefficients
in descending powers, P(1)*X^N + P(2)*X^(N-1) +...+ P(N)*X + P(N+1).
If the errors in the data, Y, are independent normal with constant
variance, POLYVAL will produce error bounds which contain at least 50% of
the predictions.

[P,S,MU] = POLYFIT(X,Y,N) finds the coefficients of a polynomial


in XHAT = (X-MU(1))/MU(2) where MU(1) = mean(X) and MU(2) = std(X).
This centering and scaling transformation improves the numerical
properties of both the polynomial and the fitting algorithm.

See also poly, polyval, roots.

- 다음의 실험 데이터 x,y가 주어졌다고 가정하고 polynomial 식을 구해보자.

17
>> x=[1 2 3 4 5];
>> y=[5.5 43.1 128 290.7 498.4];
>> p=polyfit(x,y,3)
p=
-0.1917 31.5821 -60.3262 35.3400

여기서 p는 다음을 의미한다.

이제 polyval함수를 이용하여 얼마나 fitting결과가 잘 맞는지 알아 보자.


>> help polyval
POLYVAL Evaluate polynomial.
Y = POLYVAL(P,X), when P is a vector of length N+1 whose elements
are the coefficients of a polynomial, is the value of the
polynomial evaluated at X.

Y = P(1)*X^N + P(2)*X^(N-1) + ... + P(N)*X + P(N+1)

If X is a matrix or vector, the polynomial is evaluated at all


points in X. See also polyvalm for evaluation in a matrix sense.

Y = POLYVAL(P,X,[],MU) uses XHAT = (X-MU(1))/MU(2) in place of X.


The centering and scaling parameters MU are optional output
computed by POLYFIT.

[Y,DELTA] = POLYVAL(P,X,S) or [Y,DELTA] = POLYVAL(P,X,S,MU) uses


the optional output structure S provided by POLYFIT to generate
error estimates, Y +/- delta. If the errors in the data input to
POLYFIT are independent normal with constant variance, Y +/- DELTA
contains at least 50% of the predictions.

See also POLYFIT, POLYVALM.

>> x2=1:0.1:5
x2 =
Columns 1 through 8

18
1.0000 1.1000 1.2000 1.3000 1.4000 1.5000 1.6000 1.7000
Columns 9 through 16
1.8000 1.9000 2.0000 2.1000 2.2000 2.3000 2.4000 2.5000
Columns 17 through 24
2.6000 2.7000 2.8000 2.9000 3.0000 3.1000 3.2000 3.3000
Columns 25 through 32
3.4000 3.5000 3.6000 3.7000 3.8000 3.9000 4.0000 4.1000
Columns 33 through 40
4.2000 4.3000 4.4000 4.5000 4.6000 4.7000 4.8000 4.9000
Column 41
5.0000

>> y2=polyval(p,x2);
>> plot(x,y,'o',x2,y2)
>> grid on
>>

500

450

400

350

300

250

200

150

100

50

0
1 1.5 2 2.5 3 3.5 4 4.5 5

1.5 m파일을 이용한 프로그래밍

- 현재 동작하고 있는 디렉토리(present working directory)는 pwd라는 명령을 사용하여


알 수가 있다.
>> pwd

19
ans =
C:\MATLAB7\work

- 원하는 디렉토리로 바꾸고 싶어면 cd를 사용하면 present working directory 가 바뀐다.
>> cd d:\swsung
>> pwd
ans =
d:\swsung

- m파일 만들기
MATLAB Command Window에서  File메뉴  New  m-file을 누르면 m-file을
작성할 수 있다.

- for loop 문 이용하기 (사용법은 help문을 이용하면 알 수 있다.)


다음을 타이핑하고 나서 파일 이름을 example1.m으로 원하는 directory에 저장을
하자. 이것은 for문을 이용하여 1부터 3까지 더하는 프로그램이다.

sum=0.0;
for i=1:3
i=i
sum=sum+i
end

그리고 나서 MATLAB Command Window에서 example1을 실행하면 다음과 같은


결과를 얻게 된다. 이때 pwd가 m-file과 같은 directory이어야 한다.
>> example1
i=
1
sum =
1
i=
2
sum =
3
i=

20
3
sum =
6

- if문 사용 예제 (두 값 중에 큰 값을 출력하기)
다음을 타이핑하고 나서 파일 이름을 example2.m으로 원하는 directory에 저장을
하자.
a=1.0;
b=2.0;
if (a>b)
c=a
else
c=b
end

그리고 나서 MATLAB Command Window에서 example2를 실행하면 다음과 같은


결과를 얻게 된다. 이때 pwd가 m-file과 같은 directory이어야 한다.
>> example2
c=
2

여기서 주목할 것은 MATLAB Command Window에서 m-file에서 지정한 값들을 볼 수


있다는 점이다. 즉, MATLAB Command Window에서 다음과 같이 a,b,c값을 알 수 있다.

>> a
a=
1
>> b
b=
2
>> c
c=
2
>>

- subroutine 사용하기 (help function을 이용하면 작성 방법을 알 수 있다.)

21
다음을 타이핑하고 나서 파일 이름을 example3.m으로 원하는 directory에 저장을
하자.

function [c]=example3(a,b)
if (a>b)
c=a
else
c=b
end
return

그리고 나서 MATLAB Command Window에서 example3 함수를 실행하면 다음과 같은


결과를 얻게 된다. 이때 pwd가 m-file과 같은 directory이어야 한다. 아래는1과 2를
각각 a,b에 넘겨주고 함수의 결과를 d로 받는다.

>> d=example3(1,2)
c=
2
d=
2

여기서 주목할 것은 MATLAB Command Window에서 함수에서 지정한 값들을 볼 수


없다는 점이다. 즉, 특별한 선언문이 없는 한, 함수 내에서 사용된 변수는 함수 내에서만
유효하다 (local variable).
>> a
??? Undefined function or variable 'a'.
>> b
??? Undefined function or variable 'b'.
>> d
d=
2

- 실험 테이터를 파일로 만들고 변수에 저장하기


다음과 같은 값들이 실험에서 구해졌다고 하자.
1.0 2.0
2.0 2.5

22
3.0 3.1
4.0 3.4
5.0 4.0
이것을 다음과 같이 바꾸고 저장을 example4.m으로 저장하자.
data=[
1.0 2.0
2.0 2.5
3.0 3.1
4.0 3.4
5.0 4.0];
그리고 나서 MATLAB Command Window에서 example4를 실행하면 다음과 같은
결과를 얻게 된다. 이때 pwd가 m-file과 같은 directory이어야 한다.

>> example4
>> data
data =
1.0000 2.0000
2.0000 2.5000
3.0000 3.1000
4.0000 3.4000
5.0000 4.0000

- fprintf를 이용한 파일 출력
다음과 같이 된 example5.m을 만들자.
x=[1 2 3 4 5 6 7 8 9 10];
y=[1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 10.0];

fid = fopen('result.txt','w'); %이것은 파일을 열고 이름 지정


for i=1:10
fprintf(fid,'%6.2f %12.8f \n',x(i),y(i)); %파일에 저장하기
end
fclose(fid); %파일 닫기에 해당

그리고 나서 MATLAB Command Window에서 example5를 실행하면 다음과 같은


result.txt파일이 pwd에 생성 된 것을 확인 할 수 있다.
1.00 1.10000000

23
2.00 2.20000000
3.00 3.30000000
4.00 4.40000000
5.00 5.50000000
6.00 6.60000000
7.00 7.70000000
8.00 8.80000000
9.00 9.90000000
10.00 10.00000000

1.6 Ordinary Differential Equation풀기


- ode45함수를 이용하여 ordinary differential equation을 풀어 보자.
>> help ode45
ODE45 Solve non-stiff differential equations, medium order method.
[T,Y] = ODE45(ODEFUN,TSPAN,Y0) with TSPAN = [T0 TFINAL] integrates the
system of differential equations y' = f(t,y) from time T0 to TFINAL with
initial conditions Y0. Function ODEFUN(T,Y) must return a column vector
corresponding to f(t,y). Each row in the solution array Y corresponds to
a time returned in the column vector T. To obtain solutions at specific
times T0,T1,...,TFINAL (all increasing or all decreasing), use
TSPAN = [T0 T1 ... TFINAL].

[T,Y] = ODE45(ODEFUN,TSPAN,Y0,OPTIONS) solves as above with default


integration properties replaced by values in OPTIONS, an argument created
with the ODESET function. See ODESET for details. Commonly used options
are scalar relative error tolerance 'RelTol' (1e-3 by default) and vector
of absolute error tolerances 'AbsTol' (all components 1e-6 by default).

[T,Y] = ODE45(ODEFUN,TSPAN,Y0,OPTIONS,P1,P2...) passes the additional


parameters P1,P2,... to the ODE function as ODEFUN(T,Y,P1,P2...), and to
all functions specified in OPTIONS. Use OPTIONS = [] as a place holder if
no options are set.

ODE45 can solve problems M(t,y)*y' = f(t,y) with mass matrix M that is
nonsingular. Use ODESET to set the 'Mass' property to a function MASS if
MASS(T,Y) returns the value of the mass matrix. If the mass matrix is

24
constant, the matrix can be used as the value of the 'Mass' option. If
the mass matrix does not depend on the state variable Y and the function
MASS is to be called with one input argument T, set 'MStateDependence' to
'none'. ODE15S and ODE23T can solve problems with singular mass matrices.

[T,Y,TE,YE,IE] = ODE45(ODEFUN,TSPAN,Y0,OPTIONS...) with the 'Events'


property in OPTIONS set to a function EVENTS, solves as above while also
finding where functions of (T,Y), called event functions, are zero. For
each function you specify whether the integration is to terminate at a
zero and whether the direction of the zero crossing matters. These are
the three vectors returned by EVENTS: [VALUE,ISTERMINAL,DIRECTION] =
EVENTS(T,Y). For the I-th event function: VALUE(I) is the value of the
function, ISTERMINAL(I)=1 if the integration is to terminate at a zero of
this event function and 0 otherwise. DIRECTION(I)=0 if all zeros are to
be computed (the default), +1 if only zeros where the event function is
increasing, and -1 if only zeros where the event function is
decreasing. Output TE is a column vector of times at which events
occur. Rows of YE are the corresponding solutions, and indices in vector
IE specify which event occurred.

Example
[t,y]=ode45(@vdp1,[0 20],[2 0]);
plot(t,y(:,1));
solves the system y' = vdp1(t,y), using the default relative error
tolerance 1e-3 and the default absolute tolerance of 1e-6 for each
component, and plots the first component of the solution.

See also
other ode solvers: ode23, ode113, ode15s, ode23s, ode23t, ode23tb
options handling: odeset, odeget
output functions: odeplot, odephas2, odephas3, odeprint
evaluating solution: deval
ode examples: rigidode, ballode, orbitode

- 현재 디렉토리에 다음의 미분 방정식을 m파일로 만들어서 test_func.m 제목으로 저장하자.


function [dy]=test_func(t,y)

25
dy(1,1)=-y(1)+1;
dy(2,1)=0.2*y(1)-y(2);
return
이것은 수식으로는 다음의 미분 방정식을 의미한다.

이제 이 미분 방정식은 다음과 같이 풀 수 있다.


>> [t,y]=ode45(@test_func,[0 5],[0 0]);
>> plot(t,y)
>> legend('y1','y2')

0.9

0.8
y1
0.7 y2

0.6

0.5

0.4

0.3

0.2

0.1

0
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5

- 현재 디렉토리에 다음의 미분 방정식을 m파일로 만들어서 test_func.m 제목으로 저장하자.


function [dy]=test_func(t,y)
dy(1,1)=-y(1)+1;
dy(2,1)=0.2*y(1)-y(2);
return
이것은 수식으로는 다음의 미분 방정식을 의미한다.

이제 이 미분 방정식을 푸는데 시간이 0 2 3 5에서만 결과가 나오도록 만들자.

26
>> [t,y]=ode45(@test_func,[0 2 3 5],[0 0]);
>> t
t=
0
2
3
5

>> y
y=
0 0
0.8647 0.1188
0.9502 0.1602
0.9933 0.1919

- 현재 디렉토리에 다음의 미분 방정식을 m파일로 만들어서 test_func2.m 제목으로 저장하자.


function [dy]=test_func2(t,y,a,b)
dy(1,1)=-y(1)+a;
dy(2,1)=b*y(1)-y(2);
return
이것은 수식으로는 다음의 미분 방정식을 의미한다.

이제 이 미분 방정식을 푸는데 미분 방정식의 변수에 a=1.0, b=0.2를 넣고 시간이 0 2 3 5에서


y값을 구해보자.
>> [t,y]=ode45(@test_func2,[0 2 3 5],[0 0],[],1.0,0.2);
>> t
t=
0
2
3
5
>> y
y=

27
0 0
0.8647 0.1188
0.9502 0.1602
0.9933 0.1919

28

You might also like