matlab 的循环

来源:互联网 发布:key软件怎么打开 编辑:程序博客网 时间:2024/06/05 19:03

1.while循环重复执行语句,当条件为 true。

在MATLAB 中 while循环的语法是:

while <expression>   <statements>end

while 循环反复执行程序语句只要表达式为 true。

表达式是 true,当结果不为空,并包含所有非零元素(逻辑或实际数字)。否则,表达式为 false。

a = 10;% while loop execution while( a < 20 )  fprintf('value of a: %d', a);  a = a + 1;end

当您运行该文件,它会显示以下结果:

value of a: 10value of a: 11value of a: 12value of a: 13value of a: 14value of a: 15value of a: 16value of a: 17value of a: 18value of a: 19
2.for循环是一个重复的控制结构,可以有效地写一个循环,需要执行特定次数。

语法:

在MATLAB中的 for循环的语法是:

for index = values  <program statements>          ...end
for a = 10:20   fprintf('value of a: %d', a);end

当运行该文件,它会显示以下结果:

value of a: 10value of a: 11value of a: 12value of a: 13value of a: 14value of a: 15value of a: 16value of a: 17value of a: 18value of a: 19value of a: 20
3.一个 if ... end语句由一个 if 语句和一个布尔表达式后跟一个或多个语句由 end 语句分隔。

语法

在MATLAB中 的 if 语句的语法是:

if <expression>% statement(s) will execute if the boolean expression is true <statements>end

如果表达式的计算结果为true,那么里面的代码块,如果语句会被执行。如果表达式计算为false,那么第一套代码结束后的语句会被执行。

a = 10;% check the condition using if statement    if a < 20    % if condition is true then print the following        fprintf('a is less than 20' );   endfprintf('value of a is : %d', a);

当运行该文件,它会显示以下结果:

a is less than 20value of a is : 10
4.if 语句可以跟随一个(或多个)可选的 elseif... else 语句,这是非常有用的,用来测试各种条件。

使用 if... elseif...else 语句,有几点要记住:

  • 一个 if 可以有零个或else,它必须跟在 elseif 后面(即有 elseif 才会有 else)。 

  • 一个 if 可以有零个或多个 elseif ,必须出现else。

  • elseif  一旦成功匹配,剩余的 elseif  将不会被测试。

a = 100;%check the boolean condition    if a == 10          % if condition is true then print the following        fprintf('Value of a is 10' );    elseif( a == 20 )       % if else if condition is true        fprintf('Value of a is 20' );    elseif a == 30         % if else if condition is true         fprintf('Value of a is 30' );   else        % if none of the conditions is true '       fprintf('None of the values are matching');   fprintf('Exact value of a is: %d', a );   end

上面的代码编译和执行时,它会产生以下结果:

None of the values are matchingExact value of a is: 100

1 0