3. matlab入门——控制结构、选择结构、循环结构、错误控制
一、控制结构
1、逻辑结构
顺序结构、选择结构(条件判断)、循环结构、错误控制结构;
其他:return,break,continue,input,error,keyboard,pause
二、选择结构
1、if语句

a = 6;
if rem(a,2) == 0
disp("偶数")
end
偶数
2、if-else语句

a = 8;
if rem(a,2) == 0
disp("偶数")
else
disp("奇数")
end
偶数
3、elseif语句

a = 7;
if a>0
disp('a>0')
elseif a ==0
disp('a=0')
else
disp('a<0')
end
a>0
4、switch语句


% switch
month = 4;
switch month
case{3,4,5}
season = 'spring';
case{6,7,8}
season = 'summer';
case 9
season = 'autumn';
otherwise
season = 'winter';
end
season =
'spring'
三、循环结构
1、for语句

% for
for i = 1:10
i
end
for i = 1:2:20
i
end
2、while语句


% while
a = 1;
while a < 20
a
a=a+1;
end
3、continue语句
结束本次循环,进入下次循环

4、break语句
结束循环

四、错误结构
1、try-catch结构

%% 错误结构
a = ones(3);
try
a(12,:)
catch
disp('error')
disp(lasterr)
end
error
索引超出矩阵维度。

浙公网安备 33010602011771号