Matlab if...else...end语句

if语句可以后跟一个可选的else语句,当该表达式为false时执行else语句中的代码。

语法

MATLAB中if...else语句的语法是 -

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

如果布尔表达式(expression)的值为true,那么if代码块将被执行,否则else代码块将被执行。

流程图

例子

创建脚本文件并键入以下代码 -

a = 100;
% check the boolean condition 
if a < 20 
  % if condition is true then print the following 
  fprintf('a is less than 20\n' );
else
  % if condition is false then print the following 
  fprintf('a is not less than 20\n' );
end
  fprintf('value of a is : %d\n', a);

执行上面示例代码,得到以下结果 -

a is not less than 20
value of a is : 100

上一篇: Matlab决策 下一篇: Matlab循环