Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 MATLAB 프로그래밍. 2 MATLAB MATLAB이란? mathworks 사(http://www.mathworks.com) 개발 수치해석 및 프로그래밍 환경을 제공하는 공학용 툴 특징 행렬 처리 용이 함수와 데이터의 그래프 표현 사용자 인터페이스 생성 및 다른.

Similar presentations


Presentation on theme: "1 MATLAB 프로그래밍. 2 MATLAB MATLAB이란? mathworks 사(http://www.mathworks.com) 개발 수치해석 및 프로그래밍 환경을 제공하는 공학용 툴 특징 행렬 처리 용이 함수와 데이터의 그래프 표현 사용자 인터페이스 생성 및 다른."— Presentation transcript:

1 1 MATLAB 프로그래밍

2 2 MATLAB MATLAB이란? mathworks 사(http://www.mathworks.com) 개발 수치해석 및 프로그래밍 환경을 제공하는 공학용 툴 특징 행렬 처리 용이 함수와 데이터의 그래프 표현 사용자 인터페이스 생성 및 다른 프로그래밍 언어 연결 가능 다양한 내장 함수 및 툴박스 제공 플랫폼 독립적

3 3 MATLAB 데스크탑

4 4 MATLAB 스칼라 값 배정 소수점이하 15자리까지 표현 소수점이하 4자리까지 표현

5 5 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 6 MATLAB 벡터, 행렬 콜론(:) 연산자 1부터 5까지 1씩 증가하는 행벡터 1부터 3까지 0.5씩 증가하는 행벡터 인덱스 2~4까지의 벡터 추출

7 7 MATLAB 벡터, 행렬 콜론(:) 연산자 2행, 인덱스 생략 3행, 1열과 2열 2~3행, 1~2열로 구성된 2x2 행렬 반환

8 8 MATLAB 벡터, 행렬 linspace(x1, x2, n) x1과 x2 사이의 등 간격 n개의 포인트 생성 logspace(x1, x2, n) 10 x1 과 10 x2 사이에 지수적 등 간격 n개의 포인트 생성

9 9 MATLAB 벡터, 행렬 eye(n) nxn 단위행렬(identity matrix) zeros(n,m) nxm 0행렬 ones(n,m) mxm 행렬(모든 원소의 값이 1) …

10 10 수학 연산 우선순위연산자설명 1^지수 계산 2-음부호 3* /곱셈, 나눗셈 4\ 왼쪽 나눗셈(행렬 연산) 5+ -덧셈, 뺄셈 >> y = pi / 4 >> -y^2.45 >> (-y)^2.45

11 11 행렬 연산 OperationMATLAB FormComments Array Additiona + bArray addition and matrix addition are identical Array Subtractiona – b Array subtraction and matrix subtraction are identical Array Multiplicationa. * b Element-by-element multiplication of a and b. Both arrays must be the same shape, or one of them must be a scalar Matrix Multiplicationa * b Matrix multiplication of a and b. The number of columns in a must equal the number of rows in b. Array Right Divisiona./ 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 Exponentiationa. ^ 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 MATLAB을 이용한 행렬계산 1 variable = expression * variable : 변수, 기본적으로 타 language에서의 지원 변수 와 거의 유사한 형태를 지원 EX. >> a = [1,2,3;4,5,6;7,8,9] a = 1 2 3 4 5 6 7 8 9 >> 주석문 처리는 문장앞에 “%”. 행렬에서 행 구분은 “;”, 열 구분은 “ ” 또는 “,”. 수식 표현 뒤에 “;” 를 붙이면 결 과값이 Command Windows 에 출력되지 않는다. 입력한 행렬은 Workspace 에서 확인 가능. 콜론 (:) 을 사용해서 증가나 감 소하는 벡터를 쉽게 만들수 있 다.

13 MATLAB을 이용한 행렬계산 2 >> a(1,3) ans = 3 >> a(1,3)=4 a = 1 2 4 4 5 6 7 8 9 >> a(1:2,3) ans = 4 6 >> a(1,1:3) ans = 1 2 4 >> a(1,:) ans = 1 2 4 >> a(:,:) ans = 1 2 4 4 5 6 7 8 9 >> i = 0:0.1:0.5 i = 0 0.1000 0.2000 0.3000 0.4000 0.5000

14 14 행렬 연산 예제 덧셈/뺄셈 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

15 15 행렬 연산 예제 지수 정방행렬 ^지수승 배열 연산자(.연산자) 각 원소끼리 연산.*./.^

16 Multi graphic 객체 사용하기 subplot(MNI) or subplot(M,N,I) M(행의 갯수), N(열의 갯수), I(하부영역의 순서) >> subplot(221) >> subplot(222) >> subplot(212) subplot(221)subplot(222) subplot(212)

17 PLOT 사용하기 plot(xdata, ydata, 'color_linestyle_marker') xdata와 ydata의 크기가 일치해야 한다. 그래프의 속성은 무시해도 된다. 하나의 창 안에 여러 그래프를 동시에 그리려면..  plot(x1, y1, ’ 속성1 ’, x2, y2, ’ 속성2 ’, x3, y3, ’ 속성3 ’,...)

18 그래프의 속성 가능한 선의 Color Matlab Symbol Color Matlab Symbol Color c 하늘 g 초록 m 자주 b 파랑 y 노랑 w 흰색 r 빨강 k 검은색 가능한 선의 Style Matlab Symbol Style Matlab Symbol Style - Solid line :Dotted line -- Dashed line -. Dash-dot line noneNo Line 가능한 선의 marker Matlab Symbol Marker Style Matlab Symbol Marker Style ++^ △ oov ▽ **> ▷. ● < ◁ x×pentagram ☆ Square □ hexagram¤ Diamond ◇ none No marker (default)

19 실 습 1. -pi < x < pi 일 때(단 x의 스텝은 0.05), figure(1)의 subplot(211)에 X축에 x, Y축에 a=cos(x)를 plot 하라. figure(1)의 subplot(212)에 X축에 x, Y축에 b=sin(x)를 plot 하라. figure(2)의 X축에 a, Y축에 b를 plot하라

20 실 습 1.

21 % 실습 1. x= -pi:0.05:pi; a=cos(x); b=sin(x); figure(1); subplot(211); plot(x,a); subplot(212); plot(x,b); figure(2) plot(a,b);

22 제목, 각 축의 이름, 격자 넣기 title( ‘ 그래프의 제목 ’ ) 그래프의 제목을 나타낼 때 사용한다. xlabel( ‘ X축 이름 ’ ) x축의 이름을 넣을 때 사용한다. ylabel( ‘ Y축 이름 ’ ) y축의 이름을 넣을 때 사용한다. zlabel( ‘ Z축 이름 ’ ) z축의 이름을 넣을 때 사용한다. grid 그래프 객체에 격자를 더하거나 없앤다.

23 범례, 축의 한계값 사용하기 legend(‘문자열1’,‘문자열2’,...,정수)  문자열1:첫번째 그래프에 대한 범례  문자열2:두번째 그래프에 대한 범례 axis([x1,x2,y1,y2])  x1 : x축의 최소값, x2 : x축의 최대값  y1 : y축의 최소값, y2 : y축의 최대값 xlim([x1,x2]) : x축 제한 ylim([y1,y2]) : y축 제한

24 실습 2. 실습 1의 각 그래프에 축의 이름을 붙인다. 실습 1의 각 그래프에 제목을 붙인다. 실습 1의 각 그래프에 격자를 넣는다. 실습 1의 cos(x), sin(x) 그래프를 하나의 그래프(figure(3)) 에 그리고, 범례를 넣는다.

25

26 % 실습 2. figure(1) subplot(211) xlabel('x'); ylabel('a'); title('a=cos(x)'); grid on; subplot(212) xlabel('x'); ylabel('b'); title('b=sin(x)'); grid on; figure(2) xlabel('x'); ylabel('y'); axis([-2,2,-2,2]); title('Graph of Circle'); grid on; figure(3) plot(x,a,x,b); legend('cos(x)','sin(x)'); xlabel('x'); ylabel('y'); grid on;

27 기본적인 그래픽 함수들 함 수설 명 plot x 와 y 축에 대해서 모두 선형 배율로 된 그래프 loglog x 와 y 축에 대해서 모두 log 배율로 된 그래프 semilogx x 축에 대해서는 log 배율, y 축에 대해서는 선형 배율로 된 그래프 semilogy x 축에 대해서는 선형 배율, y 축에 대해서는 log 배율로 된 그래프 plotyy 두 개의 y 축 선형 배율을 가진다.

28 28 내장 함수 Trigonometric Functions FunctionDescription cos(x) Calculates cos x, with x in radians. acos(x) Calculates cos -1 x, with the results in radians. sin(x) Calculates sin x, with x in radians. asin(x) Calculates sin -1 x, with the results in radians. tan(x) Calculates tan x, with x in radians. atan(x) Calculates tan -1 x, 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

29 29 내장 함수 Round, Exponential, Logarithm FunctionDescription [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.

30 30 내장 함수 Complex & Rational Numbers Help help 함수명 FunctionDescription 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

31 31 함수 활용 예 자유낙하 속도 측정 t=[0:2:20]’; g=9.81; m=68.1; cd=0.25; v=sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t) v : 속도(m/s) g : 중력가속도(9.81m/s 2 ) m : 질량(kg) c d : 항력계수(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

32 32 그래픽 표현 Figure plot stem stairs bar compass pie semilog semilogx semilogy plot stairs compass stem bar pie

33 33 그래픽 표현 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) 1Upper right-hand corner (default) 2Upper left-hand corner3Lower left-hand corner 4Lower right-hand cornerTo the right of the plot

34 34 그래픽 표현 Colors & Styles ColorMarker StyleLine Style yyellow.point-solid mmagentaocircle:dotted ccyanxx-mark-.dash-dot rred+plus--dashed ggreen*star no line bbluessquare wwhiteddiamond kblackvtriangle (down) ^triangle (up) <triangle (left) >triangle (right) ppentagram hhexagram no marker

35 35 그래픽 표현 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

36 36 그래픽 표현 사랑의 방정식 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

37 37 스크립트 파일 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

38 38 함수 파일 함수 형식 예제) 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

39 39 여러 개의 값 반환 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

40 40 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_

41 41 disp 함수 형식 disp( value ) 설명 명령창에 value 값 출력 예제

42 42 fprintf 함수 형식 fprintf( ‘ format ’, arglist … ) 설명 주어진 format에 맞춰 값을 출력 포맷 / 제어 코드 코드설명 %d 정수 포맷 %e e를 사용하는 과학 포맷 %E E를 사용하는 과학 포맷 %f 소수 포맷 %g %e나 %f 중에서 간단한 포맷 \n 새로운 줄로 시작 \t 탭

43 43 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 ……

44 44 대화식 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

45 45 함수호출 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함수를 호출

46 46 관계/논리 연산 관계연산자 논리 연산자 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

47 47 판정 : 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

48 48 에러함수 : error 형식 error( msg ) 설명 텍스트 메시지 msg를 출력하고 m-파일 종료 예제 if x == 0, error(‘Zero value encountered’), end f = 1 / x;

49 49 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

50 50 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)

51 51 메모리 사전 할당 t = 0:0.01:5; for i = 1:length(t) if t(i) > 1 y(i) = 1 / t(i); else y(i) = 1; 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 배열의 크기가 예측 가능하면 미리 메모리를 할당

52 52 while 구조 형식 while condition statements end 설명 condition이 참(1)인 동안 statements를 반복 수행 예제 while x > 0while(1) x = x – 3; if x < 0, break, end disp( x ) x = x – 5; end

53 53 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];

54 실습 실습 1 부터 100까지 더하기 [등차수열] 1부터 N까지 더하기 (N을 input으로 받아서 구하기) 2+2*(1/3)+2*(1/3)^2+….+ 2*(1/3)^(99) [등비수열] 2+2*(1/3)+2*(1/3)^2+….+ 2*(1/3)^(N-1) (N을 input으 로 받아서 구하기) 54

55 55 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 % 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

56 56 Gauss Elimination 실행결과 x 1 + x 2 + 2x 3 = 9 2x 1 + 4x 2 – 3x 3 = 1 3x 1 + 6x 2 – 5x 3 = 0 >> A = [ 1 1 2 ; 2 4 -3 ; 3 6 -5 ]; >> b = [ 9 1 0 ]’; >> GaussNaive(A,b) ans = 1 2 3

57 57 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


Download ppt "1 MATLAB 프로그래밍. 2 MATLAB MATLAB이란? mathworks 사(http://www.mathworks.com) 개발 수치해석 및 프로그래밍 환경을 제공하는 공학용 툴 특징 행렬 처리 용이 함수와 데이터의 그래프 표현 사용자 인터페이스 생성 및 다른."

Similar presentations


Ads by Google