Skip to content

MATLAB - Nested Switch

You can use a switch statement inside one of the cases of another switch statement. This is called nesting. A nested structure is useful for testing a value against multiple layers of conditions.

The syntax for a nested switch statement is as follows:

switch <switch_expression_outer>
case <case_expression_1>
% Statements for outer case 1
switch <switch_expression_inner>
case <inner_case_expression_A>
% Statements for inner case A
case <inner_case_expression_B>
% Statements for inner case B
otherwise
% Statements for other inner cases
end
case <case_expression_2>
% Statements for outer case 2
otherwise
% Statements for other outer cases
end

MATLAB keeps the inner and outer switch statements distinct. There are no conflicts even if the case values are the same in both.

Imagine a simple program that processes a main command and a subcommand. A nested switch is a clear way to structure this logic. In this example, we use modern string arrays for comparison, which is generally preferred over character arrays.

% Define the main command and subcommand as strings
mainCommand = "plot";
subCommand = "line";
fprintf('Processing command: %s, subcommand: %s\n', mainCommand, subCommand);
% Outer switch for the main command
switch mainCommand
case "plot"
fprintf('Entering plot configuration...\n');
% Inner switch for the plot type
switch subCommand
case "line"
fprintf('--> Executing: Draw a line plot.\n');
case "scatter"
fprintf('--> Executing: Draw a scatter plot.\n');
case "bar"
fprintf('--> Executing: Draw a bar chart.\n');
otherwise
fprintf('--> Error: Unknown plot type ''%s''.\n', subCommand);
end
case "data"
fprintf('Entering data processing...\n');
% Another nested switch could go here for data subcommands
otherwise
fprintf('Error: Unknown main command ''%s''.\n', mainCommand);
end
fprintf('Processing complete.\n');

When you run this script, it displays:

Processing command: plot, subcommand: line
Entering plot configuration...
--> Executing: Draw a line plot.
Processing complete.

Try changing subCommand to "bar" or "heatmap" to see how the inner switch and its otherwise clause work.

  • Use otherwise: It’s a best practice to include an otherwise clause in every switch statement to handle unexpected values gracefully and prevent errors.
  • Readability: Deeply nested structures (more than 2-3 levels) can become hard to read and maintain. If your logic gets too complex, consider refactoring.
  • Refactoring to Functions: For complex logic, a cleaner alternative is to break the code into smaller functions. The outer switch can call a specific function, and that function can contain its own logic (which could be another switch or an if-elseif block).
  • if-elseif-else: If your conditions involve ranges or more complex logical expressions (e.g., value > 10 && value < 20), an if-elseif-else structure is more appropriate than switch.

matlab_decisions.htm