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

如果布林表示式計算結果為真,則執行 if 程式碼塊,否則執行 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\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_decisions.htm
廣告