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