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