Docsity

Matlab Basics: Variables, Matrices, Functions, Loops and Conditional Statements, Exercises of Computer Programming

Partial preview of the text

Download Matlab Basics: Variables, Matrices, Functions, Loops and Conditional Statements and more Exercises Computer Programming in PDF only on Docsity!

Matlab

Matlab Interface

• M파일 생성 : [새 스크립트]→실행

  • clc
  • clear : 작업공간 까지
  • reshape
  • flipud, fliplr
  • 전치행렬
  • length, size
  • help
  • reshape
  • a=[1 2 3; 4 5 6; 7 8 9; 10 11 12]
  • b=reshape(a,1,12)
  • b=[1 4 7 10 2 5 8 11 3 6 9 12]
  • c= reshape(a,3,4) 1 2 3 4 5 6 7 8 9 10 11 12 1 10 8 6 4 2 11 9 7 5 3 12 1 4 7 10 2 5 8 11 3 6 9 12

ex

1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12

i=a’

j=reshape(i,1,12)

  • a와 b를 입력 받아 덧셈 연산하기
  • 함수이름과 m파일이름이 같도록(자동생성해줌) function y=a_plus_b(x1,x2) y=x1+x end

    a_plus_b(1,2) d=a_plus_b(3,4)

total= for ( i=-1:-100 ) total=total+i end % 1부터 99 까지의 홀수의 합 total= for (i=1:2:99) total=total+i end

total= for ( i=1:100 ) total=total+i end total=-total

반복문 (while)

  • for는 초기값, 증감, 최종값을 정해주지만,
  • while은 조건에 의한 반복  1+2+3+4+5+…+100=?  - 1 - 2 - 3 - 4 - 5 - …-100=?  1+3+5+7+9+…+99=?

i= while i< i=i+ end

i= total= while i< i=i+ total=total+i end

i= total= while i< i=i+ total=total-i end % 1 부터 99 까지 홀수의 합 i= total= while i< i=i+ total=total+i end

a= if a== disp(‘a는 1 입니다.’) elseif a== disp(‘a는 0 입니다.’) else disp(‘a는 1 도아니고 0 도 아닙니다.’) end a=[1 2 3 1 0 1] for i=1:1:length(a) if a(i)== disp(‘a는 1 입니다.’) elseif a(i)== disp(‘a는 0 입니다.’) else disp(‘a는 1 도 아니고 0 도 아닙니다.’) end end

ex. 학점계산

score = input(‘너의 성적은…?’) if score>= disp(‘A’) elseif score>= disp(‘B’) elseif score>= disp(‘C’) else disp(‘D’) end