다음은 MATLAB 의 간단한 설명과 선형대수에서의 예를 수학과 이지은 양이 정리한 것을 이상구교수가 수정한 것입니다. 숙제가 있을 예정이니 미리 익혀 두기 바랍니다..
성대 수학과 이상구교수
◈ 선형대수학과 MATLAB 사용법의 예 (I)
⇒ MATLAB은 강력한 수학적 능력을 갖고 있고, 또한 쉽게 주어진 상황을 코딩화 할 수 있다. 그 동안 이상구교수님께 전산수학과 행렬론 강의를 들으며 Mathematica나 Hlinprac과 같은 수학관련 도구를 들어 보고 또 간단히 나마 사용해 보았는데 MATLAB만큼 강력하지 않다고 한다. 현재 외국의 여러 나라에서도 모든 코딩을 대부분 MATLAB으로 전환하려는 추세인 듯 하다. 우리나라에서 현재 개발 중인 "셈툴로(Cemtulro)"라는 소프트웨어도 MATLAB 과 같은 구조이다.
과거에는 Fortran으로 작성되었으나, 현재는 MathWorks사에서 C++로 작성하였다. 일반적으로 MATLAB이 이용되는 범위는 수학과 관련된 계산이나 알고리즘 개발, 상황 모델링과 data분석, 여러 가지 과학과 공학적인 그래픽 표현, Graphical User Interface에 의한 에플리케이션 개발등이다.
현재 버전 5.03이 나와있는 MATLAB은 외부 프로그램, 즉 C, Fortran과 link해서 이용할 수 있는 기능도 제공하고 있다. PC뿐만 아니라 UNIX, MAC.에서도 사용할 수 있으며 이용 방법은 거의 같다.
⇒ Installation하기 위한 기본 사양
·Intel 486 프로세서 이상 (math coprocessor포함, Pentium 133이상 권장)
·RAM 16MB 이상
·Help file에는 HTML문서와 .PDF문서가 있는데 .PDF문서는 www.adobe.com
에 접속하여 얻을 수 있다.
설치 방법은 자동 설치되는 기타 소프트웨어과 동일하므로 생략
◈ MATLAB 실습
다음은 인터넷 http://www.math.utah.edu/lab/ms/matlab/matlab.html 사이트에 있는 MATLAB에 관한 기본적인 사용방법에 관한 설명을 정리하고 실제 프로그램에서 확인한 내용이다.
□%matlab □a = [ 1 2; 2 1 ] a = 1 2 2 1 □a^2 ans = 5 4 4 5 |
▶ 행렬의 기본연산
위의 예에서 a라는 matrix를 정의하고 그것의 행렬의 power(a^2)를 계산하였다.
행의 원소는 빈칸이나 (,)로 구분하고 열의 원소는 (;)으로 구분한다. 그리고 [ ]으로 닫아 준다.
□clear all □clc □a=[1 2;3 4] a = 1 2 3 4 □b=[1 2;0 1] b = 1 2 0 1 □a*b ans = 1 4 3 10 □b*a ans = 7 10 3 4
|
다음은 행렬 a와 b를 정의하고 기타 여러 가지 행렬연산을 해보았다.
행렬의 곱 a*b와 b*a의 교환이 성립하지 않음을 볼 수 있다.
□a+b ans = 2 4 3 5 □s=a+b; □inv(s) ans = -2.5000 2.0000 1.5000 -1.0000 □eig(a) ans = -0.3723 5.3723 □det(s) ans = -2 |
inv(s)는 행렬의 역행렬을 구한다.
eig(a)는 행렬의 고유치와 고유백터를 구한다.
det(s)는 행렬의 determinant를 구한다.
'clear all'은 모든 변수와 핸들이 지우고 'clc' 은 DOS에서 'cls'와 같은 기능으로 변수와 핸들에는 영향이 없이 화면을 지운다.
□c=[1 2 3; 4 5 6; 7 8 9] c = 1 2 3 4 5 6 7 8 9 □d=c' d = 1 4 7 2 5 8 3 6 9 □trace(d) ans = 15
|
행렬의 transpose는 (')으로 구하며 trace(d)는 행렬의 대각합을 구하는 연산이다.
□eye(3) ans = 1 0 0 0 1 0 0 0 1 □pascal(3) ans = 1 1 1 1 2 3 1 3 6 □magic(4) ans = 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1
|
다음은 여러 가지 특수 행렬 함수들의 예이다.
'eye(차수)'는 단위행렬(identity matrix)를 만들어 주는 행렬이며, 'pascal(3)은 pascal 의 삼각형을 구하는 함수이고 'magic'은 행과 열 그리고 대각성분의 합이 모두 같은 행렬을 만든다.
▶ System of equations
다음의 linear equation을 고려해보자
이것을
행렬 표현으로 AX=B 라 하고 A가 invertible하다고 할 때 X=A-1B로 구하는데 MATLAB에서는 X=A\B로 표현한다. ,
라 하고 해를 구하면
□A=[2 3;5 7] A = 2 3 5 7 □B=[1;0] B = 1 0 □A₩B ans = -7.0000 5.0000
|
▶ Loops
간단한 programing을 해보자.
□a=[.8 .1;.2 .0]; □x=[1;0]; □for i=1:10, x=a*x, end x = 0.8000 0.2000 x = 0.6600 0.1600 x = 0.5440 0.1320 x = 0.4484 0.1088 x= 0.3696 0.0897
|
,
라하고 island의 인구변화에 따른 X의 변화를 고려해 보자. 1행의 원소
1은 island 서부 지방의 인구비율이고 2행의 0는 동부지역의 인구비율을 나타낸다.
T단위의 시간이 경과한 후에 인구는 y=aX로 주어진다. 이 때 서부의 인구중 0.8이
머무를 확률이고 0.2가 동부로 이동할 확률이다. 한편 동부의 인구는 0.9의확률로
머무르고 서부로 이동할 확률은 0.1이다. 따라서 다음과 간은 MATLAB programing에
의해서 연속적인 인구변화의 비율을 예상할 수 있다.
x = 0.3046 0.0739 x = 0.2511 0.0609 x = 0.2070 0.0502 x = 0.1706 0.0414 x = 0.1406 0.0341 x = 0.1159 0.0281
|
이하의 출력내용은 생략함
▶ Graphing
Function of one variable
y=sin(t)를 interval t=0에서 t=10까지 하여 그려보자
□t=0: .3: 10; □y=sin(t); □y2=cos(t); □plot(t,y,'r',t,y2,'y') □ |
t = 초기값 :증가분 : 말기값
plot(t,y)는 2차원 그래프를 표현한다. 위의 경우는 sin(t)와 cos(t)의 그래프를 한 차트에 나타내었으며 'r'은 red, 'y'는 yellow로 선의 색깔을 나타낸다. 결과는 다음과 같다.
Function of two variables
function z(x,y) = x exp(-x2 - y2)의 그래프를 그려보자
처음 command의 meshdom은 -2<=x<=2, -2<=y<=2
□[x,y] = meshdom(-2:.2:2, -2:.2:2); □z=x .* exp(-x.^2 -y.^2); □mesh(z) □set(gca,'xlim',[0 25],'ylim',[0 30],'zlim',[-0.5 0.5]) □ |
를 나타내며 그래프의 작은 격자무늬는 0.2의 넓이와 0.2 높이이다. mesh는 3차원 그래프를 그리는 함수이고 xlim, ylim, zlim은 각각의 좌표축에 대한 경계를 나타낸다. 결과는 다음과 같다.
▶M-file
MATLAB언어로 쓰려진 파일들을 말하며, 연속적인 MATLAB문장들을 수행하는 script mode와 입력 매개변수와 츨력 매개변수를 다루는 function mode가 있다. M-file 는 MATLAB이 제공하는 text editor,를 이용하여 작성 할 수있다.
다음은 간단한 M-file 작성을 예로 든 것이다.
⇒ n!을 구하는 함수를 M-file로 작성한 것이다. (function mode)
먼저 File의 New에서 M-file을 클릭하여 text editor 창을 불러 온다.
그리고 다음과 같이 작성한다.
function y=fact(n) %fact(n)함수는 n에 대한 factorial 값을 구한다. y=prod(1:n); |
function 출력 변수 = 함수이름(입력변수) 로 함수를 정의하고 %에는 주석을 단다. prod는 1부터 n까지 원소들간의 곱을 나타낸다.
작성이 완료되면 함수이름(fact.m)으로 저장한다.
다음은 fact.m 함수에 의해서 5!을 계산해 본 결과이다.
□input_n=5; □y=fact(input_n) y = 120 □ |
다음은 M-file을 이용한 3차원 그래프의 출력과정이다.
title('smh graph') [x,y]=meshdom(-2:.2:2, -2:.2:3) z=x.*sin(-x.^2-y.^2)+y.*cos(-x.^2-y.^2)+tan(x)+tan(y) mesh(z) grid |
결과는 다음과 같다.
이 보고서는 MATLAB을 사용하는 초보 설명이기 때문에 간단한 설명만했고, 독자적으로 유용한 M-file을 작성하지는 못한 대신 인터넷상에 올려져 있는 유용한 M-file 자료를 다운 받아놓았다.
⑴ 호주의 모나쉬대학원생이 어군탐사를 위한 초음파탐사장비를 MATLAB으로 모델링하기 위한 M-file (MATLAB 4.2C용)
function plcdemo(action);
%PLCDEMO Continuous planar Demo.
%
% Grant Hampson, Andrew Paplinski 16-1-95
% Monash University, Melbourne Australia.
% Information regarding the play status will be held in
% the axis user data according to the following table:
play= 1;
stop=-1;
global g1
if nargin<1,
action='initialize';
end;
if strcmp(action,'initialize'),
figNumber=figure( ...
'Name','Continuous Time Beamforming Using Planar Array', ...
'NumberTitle','off', ...
'Visible','off', ...
'BackingStore','off');
%===================================
% Information for all buttons
labelColor=[0.8 0.8 0.8];
top=.95;
bottom=0.05;
btnWid=0.15;
btnHt=0.1;
right=0.95;
left=right-btnWid;
% Spacing between the button and the next command's label
spacing=-0.042;
%====================================
% The CONSOLE frame
frmBorder=0.02;
yPos=bottom-frmBorder;
frmPos=[left-frmBorder yPos btnWid+2*frmBorder 0.9+2*frmBorder];
h=uicontrol( ...
'Style','frame', ...
'Units','normalized', ...
'Position',frmPos, ...
'BackgroundColor',[0.50 0.50 0.50]);
%====================================
% The first slider
btnNumber=1;
yPos=top-(btnNumber-1)*(btnHt+spacing);
callbackStr='plcdemo(''build'');';
% Generic button information
sldPos=[left yPos-1.5*btnHt btnWid btnHt];
labelPos1=[left yPos-btnHt/2 btnWid btnHt/2];
labelPos2=[left yPos-btnHt btnWid btnHt/2];
sld1Hndl=uicontrol( ...
'Style','slider', ...
'Units','normalized', ...
'Position',sldPos, ...
'Callback',callbackStr);
uicontrol( ...
'Style','text', ...
'String','Steering', ...
'Units','normalized', ...
'Position',labelPos1);
uicontrol( ...
'Style','text', ...
'String','Direction 1', ...
'Units','normalized', ...
'Position',labelPos2);
%====================================
% The second slider
btnNumber=4;
yPos=top-(btnNumber-1)*(btnHt+spacing);
callbackStr='plcdemo(''build'');';
% Generic button information
sldPos=[left yPos-1.5*btnHt btnWid btnHt];
labelPos1=[left yPos-btnHt/2 btnWid btnHt/2];
labelPos2=[left yPos-btnHt btnWid btnHt/2];
sld2Hndl=uicontrol( ...
'Style','slider', ...
'Units','normalized', ...
'Position',sldPos, ...
'Callback',callbackStr);
uicontrol( ...
'Style','text', ...
'String','Steering', ...
'Units','normalized', ...
'Position',labelPos1);
uicontrol( ...
'Style','text', ...
'String','Direction 2', ...
'Units','normalized', ...
'Position',labelPos2);
%====================================
% The third slider
btnNumber=7;
yPos=top-(btnNumber-1)*(btnHt+spacing);
callbackStr='plcdemo(''build'');';
% Generic button information
sldPos=[left yPos-1.5*btnHt btnWid btnHt];
labelPos1=[left yPos-btnHt/2 btnWid btnHt/2];
labelPos2=[left yPos-btnHt btnWid btnHt/2];
sld3Hndl=uicontrol( ...
'Style','slider', ...
'Units','normalized', ...
'Position',sldPos, ...
'Callback',callbackStr);
uicontrol( ...
'Style','text', ...
'String','Number of', ...
'Units','normalized', ...
'Position',labelPos1);
uicontrol( ...
'Style','text', ...
'String','Sensors', ...
'Units','normalized', ...
'Position',labelPos2);
%====================================
% The fourth slider
btnNumber=10;
yPos=top-(btnNumber-1)*(btnHt+spacing);
callbackStr='plcdemo(''build'');';
% Generic button information
sldPos=[left yPos-1.5*btnHt btnWid btnHt];
labelPos1=[left yPos-btnHt/2 btnWid btnHt/2];
labelPos2=[left yPos-btnHt btnWid btnHt/2];
sld4Hndl=uicontrol( ...
'Style','slider', ...
'Units','normalized', ...
'Position',sldPos, ...
'Callback',callbackStr);
uicontrol( ...
'Style','text', ...
'String','Sensor', ...
'Units','normalized', ...
'Position',labelPos1);
uicontrol( ...
'Style','text', ...
'String','Spacing', ...
'Units','normalized', ...
'Position',labelPos2);
%====================================
% The INFO button
labelStr='Info';
callbackStr='plcdemo(''info'')';
infoHndl=uicontrol( ...
'Style','push', ...
'Units','normalized', ...
'Position',[left bottom+btnHt+0.01 btnWid btnHt], ...
'String',labelStr, ...
'Callback',callbackStr);
%====================================
% The CLOSE button
labelStr='Close';
callbackStr='close(gcf)';
closeHndl=uicontrol( ...
'Style','push', ...
'Units','normalized', ...
'Position',[left bottom btnWid btnHt], ...
'String',labelStr, ...
'Callback',callbackStr);
% Uncover the figure
hndlList=[sld1Hndl sld2Hndl sld3Hndl sld4Hndl infoHndl closeHndl];
set(figNumber, ...
'Visible','on', ...
'UserData',hndlList);
% initialise sliders to about the right values
set(sld1Hndl,'Value',.5);
set(sld2Hndl,'Value',.5);
set(sld3Hndl,'Value',.4);
set(sld4Hndl,'Value',.3);
g1 = axes( 'Units','normalized','Position',[0.04 0.10 0.72 0.73]);
contpl(0,0,8,.003,g1);
elseif strcmp(action,'build'),
%====================================
% Use slider values and calculate new graphs
axHndl=gca;
figNumber=gcf;
hndlList=get(figNumber,'Userdata');
sld1Hndl=hndlList(1);
sld2Hndl=hndlList(2);
sld3Hndl=hndlList(3);
sld4Hndl=hndlList(4);
infoHndl=hndlList(5);
closeHndl=hndlList(6);
% ====== Start of Demo
% Get values from buttons
dir1=(-90+(180*get(sld1Hndl,'Value')))*pi/180;
dir2=(-90+(180*get(sld2Hndl,'Value')))*pi/180;
m=20*get(sld3Hndl,'Value');
d=0.001+.005*get(sld4Hndl,'Value');
contpl(dir1,dir2,m,d,g1);
% ====== End of Demo
elseif strcmp(action,'info');
end; % if strcmp(action, ...
⑵ 다음은 MATLAB ftp site에서 구한 것인데 figure window에 원을 추가하고자 할 때 유용하게 사용하 수 있는 M-file의 내용이다.
function h=circle(r,x0,y0,C,Nb)
% CIRCLE adds circles to the current plot
%
% CIRCLE(r,x0,y0) adds a circle of radius r centered at point x0,y0.
% If r is a vector of length L and x0,y0 scalars, L circles with radii r
% are added at point x0,y0.
% If r is a scalar and x0,y0 vectors of length M, M circles are with the same
% radius r are added at the points x0,y0.
% If r, x0,y0 are vector of the same length L=M, M circles are added. (At each
% point one circle).
% if r is a vector of length L and x0,y0 vectors of length M~=L, L*M circles are
% added, at each point x0,y0, L circles of radius r.
%
% CIRCLE(r,x0,y0,C)
% adds circles of color C. C may be a string ('r','b',...) or the RGB value.
% If no color is specified, it makes automatic use of the colors specified by
% the axes ColorOrder property. For several circles C may be a vector.
%
% CIRCLE(r,x0,y0,C,Nb), Nb specifies the number of points used to draw the
% circle. The default value is 300. Nb may be used for each circle individually.
%
% h=CIRCLE(...) returns the handles to the circles.
%
% Try out the following (nice) examples:
%
%% Example 1
%
% clf;
% x=zeros(1,200);
% y=cos(linspace(0,1,200)*4*pi);
% rad=linspace(1,0,200);
% cmap=hot(50);
% circle(rad,x,y,[flipud(cmap);cmap]);
%
%% Example 2
%
% clf;
% the=linspace(0,pi,200);
% r=cos(5*the);
% circle(0.1,r.*sin(the),r.*cos(the),hsv(40));
%
%
%% Example 3
%
% clf
% [x,y]=meshdom(1:10,1:10);
% circle([0.5,0.3,0.1],x,y,['r';'y']);
%
%% Example 4
%
% clf
% circle(1:10,0,0,[],3:12);
%
%% Example 5
%
% clf;
% circle((1:10),[0,0,20,20],[0,20,20,0]);
% written by Peter Blattner, Institute of Microtechnology, University of
% Neuchatel, Switzerland, blattner@imt.unine.ch
% Check the number of input arguments
if nargin<1,
r=[];
end;
if nargin==2,
error('Not enough arguments');
end;
if nargin<3,
x0=[];
y0=[];
end;
if nargin<4,
C=[];
end
if nargin<5,
Nb=[];
end
% set up the default values
if isempty(r),r=1;end;
if isempty(x0),x0=0;end;
if isempty(y0),y0=0;end;
if isempty(Nb),Nb=300;end;
if isempty(C),C=get(gca,'colororder');end;
% work on the variable sizes
x0=x0(:);
y0=y0(:);
r=r(:);
Nb=Nb(:);
if isstr(C),C=C(:);end;
if length(x0)~=length(y0),
error('length(x0)~=length(y0)');
end;
% how many rings are plottet
if length(r)~=length(x0)
maxk=length(r)*length(x0);
else
maxk=length(r);
end;
% drawing loop
for k=1:maxk
if length(x0)==1
xpos=x0;
ypos=y0;
rad=r(k);
elseif length(r)==1
xpos=x0(k);
ypos=y0(k);
rad=r;
elseif length(x0)==length(r)
xpos=x0(k);
ypos=y0(k);
rad=r(k);
else
rad=r(fix((k-1)/size(x0,1))+1);
xpos=x0(rem(k-1,size(x0,1))+1);
ypos=y0(rem(k-1,size(y0,1))+1);
end;
the=linspace(0,2*pi,Nb(rem(k-1,size(Nb,1))+1,:)+1);
h(k)=line(rad*cos(the)+xpos,rad*sin(the)+ypos);
set(h(k),'color',C(rem(k-1,size(C,1))+1,:));
end;
☞ 내 행렬론 강의를 듣는 대학원생은 이 두 M-file을 실행하여 모델링하여 제출하기 바랍니다.
▶마지막으로 MATLAB을 공부하기에 유용한 사이트들을 정리하였다.
http://www.indiana.edu/~statmath
http://www.loveangel.net/bbs/board/matlab.html
mailto:alfeld@math.utah.edu
http://www.mathworks.com/education/basics.shtml
http://www.mathworks.com/education
ⓒ 2000 Prof. S.G.Lee, Dept. of Math of SungKyunKwan University