MATLAB - if...elseif...elseif...else...end 語句



一個if語句後面可以跟一個(或多個)可選的elseif...和一個else語句,這對於測試各種條件非常有用。

在使用if... elseif...else語句時,需要注意以下幾點:

  • 一個if語句可以有零個或一個else語句,並且它必須出現在任何elseif語句之後。

  • 一個if語句可以有零到多個elseif語句,並且它們必須出現在else語句之前。

  • 一旦一個elseif語句成功,則不會測試任何剩餘的elseif或else語句。

語法

if <expression 1>
   % Executes when the expression 1 is true 
   <statement(s)>

elseif <expression 2>
   % Executes when the boolean expression 2 is true
   <statement(s)>

Elseif <expression 3>
   % Executes when the boolean expression 3 is true 
   <statement(s)>

else 
   %  executes when the none of the above condition is true 
   <statement(s)>
end

示例

建立一個指令碼檔案並在其中輸入以下程式碼:

a = 100;
%check the boolean condition 
   if a == 10 
      % if condition is true then print the following 
      fprintf('Value of a is 10\n' );
   elseif( a == 20 )
      % if else if condition is true 
      fprintf('Value of a is 20\n' );
   elseif a == 30 
      % if else if condition is true  
      fprintf('Value of a is 30\n' );
   else
      % if none of the conditions is true '
      fprintf('None of the values are matching\n');
   fprintf('Exact value of a is: %d\n', a );
   end

編譯並執行上述程式碼後,將產生以下結果:

None of the values are matching
Exact value of a is: 100
matlab_decisions.htm
廣告