位置:首页 » 文章/教程分享 » MATLAB if...end 语句

一个 if ... end语句由一个 if 语句和一个布尔表达式后跟一个或多个语句由 end 语句分隔。

语法

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

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

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

流程图:

MATLAB if statement

例如:

创建一个脚本文件,并键入下面的代码:

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
' );
   end
fprintf('value of a is : %d
', a);

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

a is less than 20
value of a is : 10