matlab 해설cslee/comm/matlab_new.pdf · 2011-06-20 · 1 matlab 해설 수원대학교...

16
1 MATLAB 해설 수원대학교 전자공학과 Matlab 이란? l Matrix laboratory를 위한 행렬연산 프로그램 l 과학 공학 계산을 위한 프로그램 언어 l 데이터 처리 및 시뮬레이션 MATLAB의 대표적인 파일 l *.mat Workspace의 데이터를 저장하는 파일 l *.mdl Simulink를 저장한 파일 l *.m Function, Script를 저장함 자체가 실행파일의 역할을 함 기본 명령 l help 함수 이름l pwd present working directory를 보여준다. l ls list, 현 폴더의 파일들을 보여 준다. l who 현재 workspace 상의 모든 변수를 보여 준다. l simulink simulink의 실행 Matlab Variables Names l Begin with one of az or AZ l Have remaining characters chosen from az, AZ, 09, or _ l Have a maximum length of 31 characters l Should not be the name of a built-in variable, built-in function, or user-defined function MySym, mysym %Matlab is case sensitive. Basic 내장 variables 및 숫자 l Ans %l Eps % 가장 작은수 l pi = π l Flops % 부동연산의 횟수 l i or j = sqrt(-1) l inf = 무한대 l NaN=숫자가 아님 l Realmin, realmax % 가장 작은() 의 실수

Upload: truongtram

Post on 01-Apr-2019

266 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: MATLAB 해설cslee/comm/matlab_new.pdf · 2011-06-20 · 1 MATLAB 해설 수원대학교 전자공학과 Matlab 이란? lMatrix laboratory를위한행렬연산프로그램 l과학공학계산을위한프로그램언어

1

MATLAB 해설

수원대학교

전자공학과

Matlab 이란?

lMatrix laboratory를위한행렬연산프로그램

l과학공학계산을위한프로그램언어

l데이터처리및시뮬레이션

MATLAB의 대표적인 파일

l *.mat

– Workspace의 데이터를 저장하는 파일

l *.mdl

– Simulink를 저장한 파일

l *.m

– Function, Script를 저장함

–자체가 실행파일의 역할을 함

기본 명령

l help “함수이름”l pwd

– present working directory를보여준다.

l ls– list, 현 폴더의파일들을보여 준다.

l who–현재 workspace 상의모든 변수를보여 준다.

l simulink– simulink의실행

Matlab Variables Names

l Begin with one of a–z or A–Zl Have remaining characters chosen from

a–z, A–Z, 0–9, or _

l Have a maximum length of 31 characters

l Should not be the name of a built-in variable, built-in function, or user-defined function

– MySym, mysym %Matlab is case sensitive.

Basic 내장 variables 및 숫자

l Ans %답l Eps % 가장작은수l pi = πl Flops % 부동연산의횟수l i or j = sqrt(-1)

l inf = 무한대

l NaN=숫자가 아님l Realmin, realmax % 가장 작은(큰) 양의 실수

Page 2: MATLAB 해설cslee/comm/matlab_new.pdf · 2011-06-20 · 1 MATLAB 해설 수원대학교 전자공학과 Matlab 이란? lMatrix laboratory를위한행렬연산프로그램 l과학공학계산을위한프로그램언어

2

데이터의 format (1)

l format short ↲ % 기본적인수치표현양식! l X=[4/3 1.2345e-6] ↲l

l X = l 1.3333 0.0000 l

l format short e ↲l X ↲l X = l 1.3333e+000 1.2345e-006 l

간단한 계산기능l 1+2-8

– ans=-5

l ans/2– ans=-2.5

l a=10l b=2l c=a/bl pil sin(ans/6)l log(256)l log10(256)l log2(256)l a = 5; b = sin(a), c = cosh(a)

기본 명령

l함수 찾기

– lookfor cosine

l도움말

– help cos

– helpwin(‘cos’)– doc plot

데이터의 format (2)

l format long ↲l X ↲

l X =

l 1.33333333333333 0.00000123450000

l format bank ↲ % 소수 두 번째 자리까지 표시. l X ↲

l X =

l 1.33 0.00 l format rat ↲ % 분수식 표현! l X ↲

l X =

l 4/3 1/810045 l

데이터의 format (3)

l format hex ↲ % 16진법에 의한표현! l X ↲

l X =

l 3ff5555555555555 3eb4b6231abfd271 l

l format compact ↲l % 변수의 값을출력하는 경우발생하는 많은 blank(공백)l % 지워준다. 그래서더많은정보를 screen 또는 window에l % 표현할 수있도록해준다! l X ↲l X = l 1.3333 0.0000

Matrix 기본

l Transpose : AT = A’l Inverse : A-1= inv(A)

l Addition: A+B, A-B

lMultiplication: A*B

l Cross Product : CROSS(A,B) for length 3

l Dot Product : DOT(A,B) for length 3

l Diagonal: diag(A)

l size(A) %행렬의크기

Page 3: MATLAB 해설cslee/comm/matlab_new.pdf · 2011-06-20 · 1 MATLAB 해설 수원대학교 전자공학과 Matlab 이란? lMatrix laboratory를위한행렬연산프로그램 l과학공학계산을위한프로그램언어

3

Array & Matrices

l x=[1, 2, 3]; x=[1 2 3] %1x3 vectorl k=[1;2;3] %3x1 vectorl y=[1+j, 2+pi*i, -sqrt(-1)]l A=[1 2 3; 4 5 6; 7 8 9] or

A=[1,2,3;4,5,6;7,8,9] % 3x3 matrixl t=[0:0.1:10] % generates a row vector t that increases from 0

% to 10 in increments of 0.1

t=0:0.1:10 또한동일한결과%1x101 행렬

벡터의 생성

l a=3:9; a(6:end)– a(end-1)=10; a(end+2)=20;

l linspace(startValue,endValue,nelements)– linspace(0, 2*pi); % 100 linearly equally spaced pt

– u = linspace(0.0,0.25,5)– v = linspace(0,9,4)’– u = linspace(0.0,0.25);

l logspace(startValue,endValue,nelements)– w = logspace(1,4,4)

l u = (1:5)’l v = 1:5’

Matrices

l length(x) % returns the dimension of a vector x

l Size(A) % compute the row & column of A

l x(3)l A(2,3)l x(2:3)l A(1:2, 3)l 기존 행렬이없던곳은 0으로 채워짐

l 빈 행렬은 []로나타냄

Matrix의 생성

Matrix 예제

l D = ones(3,3)

l e = ones(2,5)

l t = zeros(3,1)

l C = eye(5)

l D = eye(3,5)

l v = [1 2 3];

– A = diag(v)

Matrix 예제

l B = [1:4; 5:8; 9:12]

– w = diag(B)

l A = [1 2 3; 4 5 6; 7 8 9];

– b = A(3,2)

– c = A(1,1)

– A(1,1) = c/b

l A = [1 2 3; 4 5 6; 7 8 9];

– A(1,4)

– A(4,4) = 11 %matrix의 확장

Page 4: MATLAB 해설cslee/comm/matlab_new.pdf · 2011-06-20 · 1 MATLAB 해설 수원대학교 전자공학과 Matlab 이란? lMatrix laboratory를위한행렬연산프로그램 l과학공학계산을위한프로그램언어

4

Matrix 예제

l A = [1 2 3; 4 5 6; 7 8 9];– A(:,1)

– A(2,:)

– A(2:3,1)

– A(1:2,2:3)

l A = ones(8,8);– A(3:6,3:6) = zeros(4,4)

l행, 열의 제거– A([1 4 5],:)=[];

– A(:,[1:3])=[];

3차원 행렬

3차원 행렬의 indexing 3차원 행렬의 예

B=imread(‘file.jpg’)

image(B)

size(B)

복소수 Matlab Workspace

•Who

•Whos

•Clear variables

•Help clear

•Diary filename: 입력및명령창 출력을파일로 저장

•Diary off

•Cd

•Dir

•!dos command

Page 5: MATLAB 해설cslee/comm/matlab_new.pdf · 2011-06-20 · 1 MATLAB 해설 수원대학교 전자공학과 Matlab 이란? lMatrix laboratory를위한행렬연산프로그램 l과학공학계산을위한프로그램언어

5

Matlab Workspace (내장 명령어)

l what

l Type

l Clockl Datel lookfor

데이터의 저장과 복원

•File/save workspace as…

•File/load workspace as…

•Save

•Save file1 a b c

•Save file2 a b c -ascii

•Load

•Load file1

•Load file2 -ascii

m-files (*.m)

l script

–명령어의나열l function

–파일명과함수명은 일치–입력, 출력 변수형식 있음

– local 변수

– subfunction사용 가능• 함수내부용• 외부에서접근불가

function 예제

l stat.m

– function [mean,stdev] = stat(x)

– n = length(x);

– mean = sum(x)/n;

– stdev = sqrt(sum((x-mean).^2/n));

l test.m

– a=randn(1,100);

– [me, devi]=stat(a)

subfunction

l stat.m

– function [mean,stdev] = stat(x)

– n = length(x);

– mean = avg(x,n);

– stdev = sqrt(sum((x-mean).^2/n));

– function mean = avg(x,n) %subfunction

– mean = sum(x)/n;

l test.m

Strings

•Str = ‘Suwon univ’;

•Size(Str)

•U=Str(4:7)

•U=Str(9:-1: 5)

•disp('text string')

•disp(Str)

Page 6: MATLAB 해설cslee/comm/matlab_new.pdf · 2011-06-20 · 1 MATLAB 해설 수원대학교 전자공학과 Matlab 이란? lMatrix laboratory를위한행렬연산프로그램 l과학공학계산을위한프로그램언어

6

String Functions

l Base2dec

l Bin2dec

l Char

l Dec2base

l Dec2bin

l Dec2hex

l double

String Functions

•Fprintf

•Hex2dec

•Hex2num

•Int2str

•Sprintf

•Sscanf

•str2num

Functions for Manipulating Polynomials

Vector addition, subtraction inner & outer product

Page 7: MATLAB 해설cslee/comm/matlab_new.pdf · 2011-06-20 · 1 MATLAB 해설 수원대학교 전자공학과 Matlab 이란? lMatrix laboratory를위한행렬연산프로그램 l과학공학계산을위한프로그램언어

7

내장함수의 벡터연산 Array Operator

Array 연산의 예

Character set 보기 및 설정

l slCharacterEncoding() returns the current MATLAB character set encoding.

l slCharacterEncoding(encoding)

– ibm-1363_P11B-2000

– 'US-ASCII'

– 'UTF-8'

– 'Shift_JIS'

– 'ISO-8859-1'

M-files: Scripts and Function Files

•Script m-file

• test1.m

•Function m-file : Primary function

• function [out1,out2, ...]=filename(in1,in2, ...)

• test2.m

• nargin, nargout

•Subfunction

•Primary function file 내부에서만사용가능

Page 8: MATLAB 해설cslee/comm/matlab_new.pdf · 2011-06-20 · 1 MATLAB 해설 수원대학교 전자공학과 Matlab 이란? lMatrix laboratory를위한행렬연산프로그램 l과학공학계산을위한프로그램언어

8

examplel File1.m ---- Script m-file

[a,b]=addiff(2,4);save result.dat a b –ascii %저장

sprintf(‘sum =%d\ndiff=%d’,a,b) %화면에표시

l Addiff.m---- function m-filefunction [isum, idiff] = addiff(a,b)

%이 프로그램은두수의합과차를

%구하는프로그램입니다.

if nargin ~= 2 error; end

if nargout ~=2 error; end

isum=a+b;

idiff=abs(a-b);

Mathematical Operations and Functions:

l Lower Case letter

l +, -, *, /, \, ^ (power), ' (transpose)– 5^2, 22/2, 2\22

l log, log10, exp, sqrt, det (determinant)l inv, eig, rankl real, imag, abs, conj

Basic Functions

l sin, cos, tan, asin : arcsinel acos, atan, sinh, cosh, tanh, asinhl abs : 절대치, sqrt : 제곱근, real : 실수부l imag : 허수부, conj : 공액복소수

l round : 반올림, fix : 버림l sign : signum, rem : 나머지

l exp : 밑이 e인 지수, log : 자연로그l log10 : 상용로그

• < less than

• <= less than or equal

• == equal

• > greater than

•>= greater than or equal

•~= not equal

•xor

Relational Operators

Logical Operators

l & % AND

l | % OR

l~ % NOT

Loops and Conditional Structures

•for

•While

•If~else

•Switch ~ Case

Page 9: MATLAB 해설cslee/comm/matlab_new.pdf · 2011-06-20 · 1 MATLAB 해설 수원대학교 전자공학과 Matlab 이란? lMatrix laboratory를위한행렬연산프로그램 l과학공학계산을위한프로그램언어

9

For loop

for variable=expressionstatement;

statement;

...

end

Example

l For k=1:20

x(k) = sin(k*2*pi/20);

End

x

WHILE Loop

while expressionstatement;statement;...

end

Example

l N! 구하기

N=5;i=1;

R=1;

while i<=N

R=i*R

i=i+1;

end

R

IF, ELSE, ELSEIF

if expression, statement, ... , statement, ...elseif expression2, statement, ... ,

statement, ... ,else statement, ... .end

Example

while 1

disp('*********Menu***************')

disp('* A: *')

disp('* B: *')

disp('* C: *')

disp('****************************')

n=input('Type string : ','s');

if n == 'A' disp('You typed A')

elseif n == 'B' disp('You typed A')

elseif n == 'C' disp('You typed C')

else

disp('Please type character in the menu')

end

end

Page 10: MATLAB 해설cslee/comm/matlab_new.pdf · 2011-06-20 · 1 MATLAB 해설 수원대학교 전자공학과 Matlab 이란? lMatrix laboratory를위한행렬연산프로그램 l과학공학계산을위한프로그램언어

10

example

while 1

n=input('Type any number(99:exit) : ');

if n==99 break; end

sprintf('You typed number %d',n)

end

sprintf('You typed number %d, Bye!',n)

CASE SWITCH statementCASE is part of the SWITCH statement syntax, whose

general form is:

SWITCH switch_expr

CASE case_expr,

statement, ..., statement

CASE {case_expr1, case_expr2, case_expr3,...}

statement, ..., statement

...

OTHERWISE,

statement, ..., statement

END

example

aaa =4;

switch aaa

case 1, disp('Number is 1')

case 2, disp('Number is 2')

case 3, disp('Number is 3')

case {4,5,6,7,8,9}, disp('Number is 4-9')

otherwise, disp('Number is out of 1-9')

end

Plotting and Graphics•plot, loglog, semilogx, semilogy, polar

•t=0:2*pi*2/50:2*pi*2*2;

•Y=sin(t);

•Plot(t,Y)

•Subplot(232);plot(t,Y)

•legend(‘sine(t)’)

•legend off

•ezplot

•plot3

Plot (계속)

•title('Title of the Figure'), •xlabel(‘\bf{X-axis Label}')

•ylabel('Y-axis Label‘, 'fontsize',15 )•gtext('Text for annotation') % for mouse positioned text•text(x, y, 'Text for annotation'), grid

•Ex) y=sinc(t)=1, t=0

y=sinc(t)=sin(pi*t)/(pi*t), t ≠0

•Ex) t=-5:0.01:5;plot(t,sinc(t)); legend(‘sinc(t)=sin(\pit)/\pit’)

Plot (계속)

l x = linspace(0,2*pi); %100 points

l y = sin(x);

l plot(x,y);

l plot(x,y,’yo’)l plot(x,y,’r--’)l plot(x,y,’kd--’)

Page 11: MATLAB 해설cslee/comm/matlab_new.pdf · 2011-06-20 · 1 MATLAB 해설 수원대학교 전자공학과 Matlab 이란? lMatrix laboratory를위한행렬연산프로그램 l과학공학계산을위한프로그램언어

11

Axis scaling

l x = linspace(0,3);

l y = 10*exp(-2*x);

l plot(x,y);

l semilogy(x,y); grid on

Multiple plot

l x = linspace(0,2*pi);

l subplot(2,2,1);l plot(x,sin(x)); axis([0 2*pi -1.5 1.5]); title(’sin(x)’);l subplot(2,2,2);

l plot(x,sin(2*x)); axis([0 2*pi -1.5 1.5]); title(’sin(2x)’);l subplot(2,2,3);l plot(x,sin(3*x)); axis([0 2*pi -1.5 1.5]); title(’sin(3x)’);l subplot(2,2,4);l plot(x,sin(4*x)); axis([0 2*pi -1.5 1.5]); title(’sin(4x)’);

Plot Annotation

l D = load(’pdxTemp.dat’); m = D(:,1); T = D(:,2:4);

l plot(m,t(:,1),’ro’,m,T(:,2),’k+’,m,T(:,3),’b-’);l xlabel(’Month’);l ylabel(’Temperature ({}^\circ F)’);l title(’Monthly average temperature at PDX’);l axis([1 12 20 100]);

l legend(’High’,’Low’,’Average’,2);

l Line_Color =get(gca,'colororder')

l Line_Type =get(gca,'Linestyleorder')

l set(0,'DefaultAxesColororder',[0 0 0],'DefaultAxesLineStyleOrder','-|-.|--|:')

l set(gca, 'xgrid', 'on', 'gridlinestyle', '-.')

l set(gca,'xtick',[0:0.4:2 2.5 3 3.5 4 4.5 5])

Page 12: MATLAB 해설cslee/comm/matlab_new.pdf · 2011-06-20 · 1 MATLAB 해설 수원대학교 전자공학과 Matlab 이란? lMatrix laboratory를위한행렬연산프로그램 l과학공학계산을위한프로그램언어

12

l t_label=str2mat('I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII')

l set(gca,'xticklabel',t_label)

l set(gco,'color','r','Linewidth',15)

l set(gca,'xlim', [min(t) max(t)],'ylim',[-1.5 1.5])

l set(gca,'nextplot','add','xlim',[min(t) max(t)]) ↲ %hold on

l set(gca,'nextplot',‘replcae','xlim',[min(t) max(t)]) ↲ %hold off

special symbols

l h=text(300,.25*exp(-.005*300),...

l '\bullet\leftarrow\fontname{times}0.25{\ite}^{-0.005{\itt}} .at {\itt}=300');

[표3-2] 특수문자표

Plot Marker

Page 13: MATLAB 해설cslee/comm/matlab_new.pdf · 2011-06-20 · 1 MATLAB 해설 수원대학교 전자공학과 Matlab 이란? lMatrix laboratory를위한행렬연산프로그램 l과학공학계산을위한프로그램언어

13

Plot Lines 종합

Menu의 사용

l line_color=['r','g','b']; l str='y'; l

l t=-2*pi:1/100:2*pi; l y=sin(t); l

l while(1) l if str=='y' l k=menu('선의 색을 결정','red','green','blue'); l plot(t,y,line_color(k)) l R=input('계속하려면 ''y''를 type! :','s'); l str=lower(R); l else l break; l end l end

questdlg 사용

l str=questdlg('계속하기를원합니까?','선택사항','Yes','No','No');

messagebox

l msgbox(message,title,'icon')

l icon– 'error', 'help', 'warn'

File I/O(FPRINTF, SSCANF, FGETL, FGETS,

FREAD, INPUT)

lOpening and closing filesl example : fid =fopen('pen.dat','r')l 'r' : readingl 'w' : wrightingl 'a' : appendingl 'r+' : reading and wrightingl status = fclose(fid);l status = fclose('all');

– ( 0 : successful, -1 : unsuccessful )

Page 14: MATLAB 해설cslee/comm/matlab_new.pdf · 2011-06-20 · 1 MATLAB 해설 수원대학교 전자공학과 Matlab 이란? lMatrix laboratory를위한행렬연산프로그램 l과학공학계산을위한프로그램언어

14

File I/O

l Reading Binary Data Filesl fread : reads binary data files

l example : fid = fopen('penny.dat', 'r');l A = fread(fid);l status = fclose(fid);

Controlling Position in a File

l Writing Formatted Text Files and Stringsl %e for exponential notation

l %f for fixed point notation

l %g which automatically selects the shorter of %e and %f

l Reading Formatted Text Files and Strings

l %s to match a string

l %d to match a decimal number

l %f to match a floating point value

Matlab Debugger

l dbstop : set breakpoint

l dbclear : remove breakpoint

l dbcont : resume execution

l dbstack : list who called whom

l dbstatus : list all break point

l dbstep : execute one or more lines

l dbtype : list M-file with line numbers

l dbup : change local workspace context

l dbquit : quit debug mode

Example

l dbstop in mfile

l dbstop in mfile at linenumber

l dbtype mfile 1:10 % type from line 1 to line 10

l dbstack % display function call stack

l dbclear all; dbclear in mfile at 4

l dbstatus % lists all breakpoints

Data Symbolic math

l sym– Construct symbolic numbers, variables and objects.

– S = SYM(A) constructs an object S, of class 'sym', from A. If the input argument is a string, the result is a symbolic number or variable. If the input argument is a numeric scalar or matrix, the result is a symbolic representation of the given numeric values.

– sym(1/10,'f'), sym(4/3,'r')

– digits(10), sym(4/3,'d')

– delta = sym('1/10')

Page 15: MATLAB 해설cslee/comm/matlab_new.pdf · 2011-06-20 · 1 MATLAB 해설 수원대학교 전자공학과 Matlab 이란? lMatrix laboratory를위한행렬연산프로그램 l과학공학계산을위한프로그램언어

15

l syms

l SYMS arg1 arg2 ... real

l is short-hand notation for

l arg1 = sym('arg1','real');

l arg2 = sym('arg2','real'); ...

l syms k positive

l is equivalent to:

l k = sym('k','positive');

251+

rho=sym(‘(1+sqrt(5))/2’)

f=rho^2 –rho +1

simplify(f)

syms a b

f=a+b

symbolic math functions

l syms x y z

l r=sqrt(x^4)

– r(2) 를구하려면

– subs(r, 2) % 4

l r2=sqrt(x^2 + y^2)

– r2(1,2) 를 구하려면

– subs(r2, {x,y},{1,2})

l subs(sqrt(x^2 + y^2), {x,y},{sym(‘alpha’),2}

l sinc(x)= sin(pi*x)/(pi*x)

Toolboxes

•control system

•signal processing

•neural network

•Communications

•…….

Control System

Page 16: MATLAB 해설cslee/comm/matlab_new.pdf · 2011-06-20 · 1 MATLAB 해설 수원대학교 전자공학과 Matlab 이란? lMatrix laboratory를위한행렬연산프로그램 l과학공학계산을위한프로그램언어

16