1 / 42

MATLAB 프로그래밍

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

Download Presentation

MATLAB 프로그래밍

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. MATLAB 프로그래밍

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

  3. MATLAB 데스크탑

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

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

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

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

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

  10. 수학 연산 >> y = pi / 4 >> -y^2.45 >> (-y)^2.45

  11. 행렬 연산

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

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

  14. 내장 함수 • Trigonometric Functions >> sqrt(2) ans = 1.4142

  15. 내장 함수 • Round, Exponential, Logarithm

  16. 내장 함수 • Complex & Rational Numbers • Help • help 함수명

  17. 함수 활용 예 • 자유낙하 속도 측정 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/s2) m : 질량(kg) cd : 항력계수(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

  18. 그래픽 표현 • Figure • plot • stem • stairs • bar • compass • pie • semilog • semilogx • semilogy plot stem stairs bar compass pie

  19. 그래픽 표현 • 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)

  20. 그래픽 표현 • Colors & Styles

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

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

  23. 스크립트 파일 • 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

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

  25. 여러 개의 값 반환 • 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

  26. 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_

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

  28. fprintf 함수 • 형식 • fprintf( ‘ format ’, arglist … ) • 설명 • 주어진 format에 맞춰 값을 출력 • 포맷 / 제어 코드

  29. 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 ……

  30. 대화식 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

  31. 함수호출 • 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함수를 호출

  32. 관계/논리 연산 • 관계연산자 • 논리 연산자

  33. 판정 : 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

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

  35. 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

  36. 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)

  37. 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 메모리 사전 할당 배열의 크기가 예측 가능하면 미리 메모리를 할당

  38. 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

  39. 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];

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

  41. 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

  42. 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

More Related