Matlab if...else...end語句

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

上一篇: Matlab決策 下一篇: Matlab迴圈