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

if 语句后面可以跟一个可选的 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

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

流程图:

MATLAB if...else statement

例如:

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

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

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

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