Skip to content

MATLAB - Switch Statement

In MATLAB, a switch statement provides an elegant way to conditionally execute one block of code from several choices based on the value of a single variable or expression. It is a more readable alternative to a long series of if-elseif-else statements, especially when dealing with a variable that can take on a set of discrete, known values.

The switch block evaluates a switch_expression and then compares its value against the expression in each case statement. When a match is found, MATLAB executes the code within that case and then exits the switch block. If no cases match, the optional otherwise block is executed.

A case is considered a match if:

  • For numeric types, the case_expression is equal to the switch_expression (e.g., 5 == 5).
  • For modern string arrays (using double quotes), the expressions are equal (e.g., "hello" == "hello").
  • For legacy character vectors (using single quotes), strcmp(case_expression, switch_expression) returns true.
  • For a cell array case_expression, at least one element of the cell array matches the switch_expression.

The otherwise block is optional but highly recommended as a best practice to handle unexpected values and prevent errors.

The fundamental syntax of a switch statement in MATLAB is:

switch switch_expression
case case_expression_1
% Code to execute if switch_expression matches case_expression_1
statements_1
case case_expression_2
% Code to execute if switch_expression matches case_expression_2
statements_2
case {case_expression_3, case_expression_4} % Grouping multiple cases
% Code to execute for either case 3 or 4
statements_3_4
otherwise
% Code to execute if no other case matches
otherwise_statements
end

Let’s create a modern example where we process a user command, represented by a string. This approach is common in interactive command-line tools. Save the following code in a file named processCommand.m.

function processCommand(command)
% processCommand Processes a command string using a switch statement.
% Example: processCommand("plot")
switch command
case "plot"
disp("Generating a sample plot...");
figure; % Create a new figure window
plot(1:10, rand(1, 10));
title("Random Data Plot");
case {"list", "show"} % Handle multiple cases with a cell array
disp("Listing available files:");
disp("- data.csv");
disp("- report.docx");
case "exit"
disp("Exiting application. Goodbye!");
otherwise
% It's good practice to warn the user about invalid input
warning('Invalid command: "%s". Type ''help processCommand'' for options.', command);
end
end

Now, run this function from the MATLAB Command Window with different inputs:

processCommand("list")
Listing available files:
- data.csv
- report.docx
processCommand("plot")
Generating a sample plot...
% A new plot window appears
processCommand("delete")
Warning: Invalid command: "delete". Type 'help processCommand' for options.
  • Always include otherwise: This makes your code more robust by gracefully handling unexpected values instead of failing silently or causing errors later.
  • Use string arrays (double quotes): For text comparison, modern string arrays are generally preferred over character vectors (single quotes) as they behave more intuitively.
  • Group common cases: Use cell arrays {} to group multiple cases that should execute the same code. This avoids code duplication.
  • Avoid overly complex logic: If your conditions involve complex logical comparisons (>, <, &&, ||), an if-elseif-else structure is often more appropriate and readable.