MATLAB - 巢狀 switch 語句



可以在外層 switch 語句的語句序列中包含一個 switch 語句。即使內層和外層 switch 語句的 case 常量包含公共值,也不會發生衝突。

語法

巢狀 switch 語句的語法如下:

switch(ch1) 
   case 'A' 
      fprintf('This A is part of outer switch');
      switch(ch2) 
         case 'A'
         fprintf('This A is part of inner switch' );
         
         case 'B'  
         fprintf('This B is part of inner switch' );
      end   
   case 'B'
      fprintf('This B is part of outer switch' );
end

示例

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

a = 100;
b = 200;
switch(a) 
   case 100 
      fprintf('This is part of outer switch %d\n', a );
      switch(b) 
         case 200
            fprintf('This is part of inner switch %d\n', a );
      end
end

fprintf('Exact value of a is : %d\n', a );
fprintf('Exact value of b is : %d\n', b );

執行該檔案後,將顯示:

This is part of outer switch 100
This is part of inner switch 100
Exact value of a is : 100
Exact value of b is : 200
matlab_decisions.htm
廣告
© . All rights reserved.