본문 바로가기

공부/프로그래밍

matlab(매틀랩) programing 강의 180402

2015 버전 기준


논리값을 이용한 여러가지 경우와 if문을 이용한 계산을 보자.


if의 형식은


if 조건식

 내용

end 


로 구성 여러가지 경우를 표현할 때는


if 조건식

 내용

elseif 조건식

 내용

else

 내용

end


반복문은 for를 사용한 것으로


for 1:10

 내용

end


로 1:10이라고 하면 1부터 10 열번 반복한다는 이야기이다.

여기에 변수를 넣거나 해서 반복횟수를 사용자에게 정하게 할 수 있다.


any(x) : x에 1이 하나라도 있다면 1 출력



>> x=[-3 0 0 2 6 8]

>> y=[-5 -2 0 3 4 10]

>> z=(x>y)


z =


     1     1     0     0     1     0


>> x(z)


ans =


    -3     0     6


----------------------------------------


>> x=[ 5 -3 0 0 8 ]

x =

     5    -3     0     0     8



>> x([1 5])

ans =

     5     8


>> x(logical([1 0 0 0 1]))

ans =

     5     8


----------------------------------------


>> x= randi([1 55],4 ,4)


x =


    45    35    53    53

    50     6    54    27

     7    16     9    45

    51    31    54     8


>> find(x>10)


ans =


     1

     2

     4

     5

     7

     8

     9

    10

    12

    13

    14

    15


>> x(find(x>10))=10


x =


    10    10    10    10

    10     6    10    10

     7    10     9    10

    10    10    10     8


-----------------------------

>> x=randi([1 55] , 4 , 4)


x =


    24    37    38    37

    51     2    42    10

    44    47    41    39

    53    52    22     2

>> [row col]=find(x>10)


row =


     1

     2

     3

     4

     1

     3

     4

     1

     2

     3

     4

     1

     3



col =


     1

     1

     1

     1

     2

     2

     2

     3

     3

     3

     3

     4

     4


---------------------------

find(조건식) 인덱스 번호 구하기

[row col] = find(조건식) 행렬 구하기

x(find(조건식)) 실제 값 구하기

length(find(조건식)) 특정 조건의 원소 개수 구하기


---------------------------

스크립트 작성

score=input('Enter(as a vector) the scores of the three test');

ave_grade=(score(1)+score(2)+score(3))/3;

disp('The acerage grade is:')

disp(ave_grade)



if ave_grade<60

    disp('The student did not pass the course');           

else 

    disp('The student passed the course');

end


실행은 스크립트명으로 매틀랩에서 실행

배열로 인풋 [x1 x2 x3] 또는 배열을 가진 변수로

else if는 elseif로 써야함

if ave_grade>=90

    disp('A');

elseif ave_grade>=80 && ave_grade<=89

    disp('B');

elseif ave_grade>=70 && ave_grade<=79

    disp('C');

elseif ave_grade>=60 && ave_grade<=69

    disp('D');

else 

    disp('F');

end


or


if ave_grade>=90

    disp('A');

elseif ave_grade>=80

    disp('B');

elseif ave_grade>=70

    disp('C');

elseif ave_grade>=60

    disp('D');

else 

    disp('F');

end

-----------------------------


>> 20 < 30 < 59 < 30


ans =


     1


>> 20 < 30 < 59 < -1


ans =


     0


제대로 값 안나옴

 ---------------------------


for k= 5:10:35

x=k^2


x= -2*pi:0.01:2*pi;

    l=length(x);

    for i=1:l

    if x(i)< -pi

        y(i)=-1;

    elseif x(i)<=pi

        y(i)=cos(x(i));

    elseif x(i)>pi

        y(i)=-1;

        

    end

    

end

728x90