MATLAB - 巢狀if語句



在 MATLAB 中,巢狀 if-else 語句總是合法的,這意味著您可以將一個 if 或 elseif 語句巢狀在另一個 if 或 elseif 語句中。

語法

巢狀 if 語句的語法如下:

if <expression 1>
   % Executes when the boolean expression 1 is true 
   if <expression 2>
      % Executes when the boolean expression 2 is true    
   end
end

您可以以類似於巢狀 if 語句的方式巢狀 elseif...else。

示例

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

a = 100;
b = 200;
   % check the boolean condition 
   if( a == 100 )
   
      % if condition is true then check the following 
      if( b == 200 )
       
         % if condition is true then print the following 
         fprintf('Value of a is 100 and b is 200\n' );
      end
       
   end
   fprintf('Exact value of a is : %d\n', a );
   fprintf('Exact value of b is : %d\n', b );

執行檔案後,將顯示:

Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
matlab_decisions.htm
廣告
© . All rights reserved.