Matlab嵌套switch语句

可以将一个switch作为外部switch语句序列的一部分。即使内部和外部switchcase常数包含公共值,也不会产生任何冲突。

语法

嵌套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决策 下一篇: Matlab循环