Matlab控制流
for循环
while循环
if-else-end结构
switch-case结构
try-catch结构
第1页/共37页
For循环结构
for n = array
{commands}
end
>>for n=1:10
x(n)=sin(n*pi/10);
end
>>x
x =
Columns 1 through 7
Columns 8 through 10
第2页/共37页
for循环不能用for循环内重新赋值循环变量n来终止
在for循环内接受任何有效的MATLAB数组
for循环可按需要嵌套
当有一个等效的数组方法来解给定的问题时,应避免用for循环
为了得到最大的速度,在 for循环被执行之前,应预先分配数组
for循环的重要说明
第3页/共37页
>>for n=1:10
x(n)=sin(n*pi/10);
n=10;
>>end
>>x
x =
Columns 1 through 7
Columns 8 through 10
第4页/共37页
>> data=[3 9 45 6; 7 16 -1 5]
data =
3 9 45 6
7 16 -1 5
>>for n=data
x=n(1)-n(2)
end;
x =
-4
x =
-7
x =
46
x =
1
第5页/共37页
>>for n=1:5
for m=5:-1:1
A(n,m)=n^2+m^2;
end
disp(n)
end
1
2
3
4
5
>>A
A =
2 5 10 17 26
5 8 13 20 29
10 13 18 25 34
17 20 25 32 41
26 29 34 41 50
第6页/共37页
>> n=1:10;
>>x=sin(n*pi/10)
x =
Columns 1 through 7
Columns 8 through 10
第7页/共37页
>>x=zeros(1,10); % preallocated memory for x
>>for n=1:10
x(n)=sin(n*pi/10);
end;
第8页/共37页
while循环结构
while expression
{commands}
end
>> num=0;EPS=1;
>> while (1+EPS)>1
EPS=EPS/2;
num=num+1;
end
>> num
num =
53
>> EPS=2*EPS
EPS =
-016
第9页/共37页
if-else-end分支结构
if expression
{commands}
end
if expression
commands evaluated if True
else
commands evaluated if False
end
if expression1
commands evaluated if expression1 is True
elseif expression2
commands evaluated if expression2 is True
elseif ……
.
else
commands evaluated if no other expression is True
end
第10页/共37页
matlabm文件和函数句柄PPT课件 来自淘豆网m.daumloan.com转载请标明出处.