一个if...end
语句由一个if
语句和一个布尔表达式组成,后跟一个或多个语句。它是由end
语句分隔的语句块。
语法
在MATLAB中,if
语句的语法是 -
if <expression>
% statement(s) will execute if the boolean expression is true
<statements>
end
如果表达式(expression
)计算结果为true
,则if
语句中的代码块将被执行。如果表达式的计算结果为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\n' );
end
fprintf('value of a is : %d\n', a);
执行上面示例代码,得到以下结果 -
a is less than 20
value of a is : 10