Lesson 4 Flow Control and Functions
4.1. Flow Control
for - 지정된 횟수를 반복하는 for 루프
지정된 횟수만큼 루프에서 명령문 그룹을 실행합니다.
for variable=expression, statement ; ... ; statement ; end
for index = values, statements, end
참고 항목 end, break, continue, parfor, return, switch, colon, if
if - 조건이 true인 경우 명령문 실행
표현식을 실행하고 표현식이 true인 경우 명령문 그룹을 실행합니다.
if expression, statements, end
elseif expression, statements ;
else statements ;
end
∙ expression에 쓰이는 비교 연산자: ==, <, >, <=, >=, ~= (not equal)
∙ expression에 쓰이는 논리 연산자: &&, ||
t = -10:0.01:10 ;
for i=1:length(t)
if t(i)==0, x(i)=1 ;
else x(i)=sin(pi*t(i))/(pi*t(i)) ;
end
end
plot(t,x,'LineWidth',2)
axis([-10 10 -0.5 1.5])
grid on
xlabel('time (sec)')
ylabel('sinc(t)')
title('sinc function')
0인경우는 극한값 1 , 아닌경우는 x(i)값
LineWidth : 선 조절하게 하는 속성
% rectangular.m
clear all; clf;
t = -2:0.001:2 ;
x = zeros(1,length(t)) ;
for i=1:length(t), if t(i)>-1/2 && t(i)<1/2,
x(i)=1 ;
end
end
plot(t,x,'LineWidth',2)
axis([-2 2 -0.5 1.5])
grid on
xlabel('time (sec)'), ylabel('rect(t)'), title('rectangular function')
■ while (>> help while), switch (>> help switch)
■ break (>> help break), continue (>> help continue)
switch switch_expression
case case_expression
statements
case case_expression
statements
...
otherwise
statements
end
4.2. Function
■ Function (>> help function) function output_var = function_name( input_var1, input_var2, ..., input_varn )
% 'help function_name'을 명령창에 입력했을 때 나오는 주석
⋮
output_var = ..
function은 따로 file을 만들어, file_name을 function_name.m으로 한다. function file은 독립적으로 실행할 수 없고, 입력변수를 넣어 call해야 함
하나의 함수 파일에 여러 개의 함수를 넣을 수 있으나, 첫 번째 함수의 이름으로 저장해야 하며, 함수의 마지막에 end를 넣어 구분해야 한다. ➠ ‘function’에 대한 도움말 창에서 ‘Multiple Functions in a File’ 참고
function y=fn_u(t)
% unit step function help로 치면 설명나옴
y=zeros(1,length(t));
for i=1:length(t)
if t(i)==0
y(i)=0.5;
elseif t(i)>0
y(i)=1;
end
end
함수는 명령창에 t=-5:0.001:5; plot(t, fn_sinc(t)) 요런식으로 직접 입력해서 불러옴
과제 완성!
코드는 .. 우리학교 학우분들이 볼수있기때문에 비밀..로!
'✍2021,2022 > MATLAB' 카테고리의 다른 글
드디어~ Convolution (0) | 2021.10.03 |
---|---|
MATLAB 실습 필기(신호 및 시스템) (0) | 2021.09.09 |