English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

MATLAB Nested Switch Statements

MATLAB Conditional Statements

There may be a switch as part of the statement sequence of an external switch. There will be no conflict even if the case constants of the internal and external switches contain common values.

Syntax

The syntax of nested switch statements 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

Online Example

Create a script file and enter 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);
It displays when the file is run-
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 Conditional Statements