位置:首頁 > 高級語言 > Matlab教學 > MATLAB 嵌套switch語句

MATLAB 嵌套switch語句

這是可能的的switch 一部分外 switch 語句序列。即使case 常量的內部和外部的switch 含有共同的值,冇有衝突出現。

語法:

嵌套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
', a );
         switch(b) 
            case 200
               fprintf('This is part of inner switch %d
', a );
         end
end
fprintf('Exact value of a is : %d
', a );
fprintf('Exact value of b is : %d
', 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