MATLAB - The Nested switch Statements

Advertisements


It is possible to have a switch as part of the statement sequence of an outer switch. Even if the case constants of the inner and outer switch contain common values, no conflicts will arise.

Syntax:

The syntax for a nested switch statement is as follows:

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

Example:

Create a script file and type the following code in it:

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 );

When you run the file, it displays:

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


Advertisements
Advertisements