Switch-Case Statements
A switch statement is an alternative to if-elseif-else for the specific case of comparing one value against several possible exact matches.
Anything a switch statement can do could also be written with if-elseif, but when you’re checking a single variable against a list of specific values, switch is often easier to read.
The MATLAB Help Center has documentation on switch.
Syntax
switch expression
case value1
statements1
case value2
statements2
otherwise
statements3
end
MATLAB evaluates expression once, then compares the result against each case value in order.
The statements under the first matching case run, and then MATLAB jumps straight to after the end keyword - unlike some other languages, MATLAB does not fall through to the next case.
If nothing matches, the otherwise block runs; like else, it’s optional.
For example:
status_code = 2;
switch status_code
case 1
disp('Nominal')
case 2
disp('Warning')
case 3
disp('Critical')
otherwise
disp('Unknown status code')
end
Warning
Matching Multiple Values in One Case
A single case can match more than one value by listing them in curly braces, {}.
This is a place where switch is noticeably more compact than the equivalent if-elseif.
Example: Propulsion Type Lookup
Question
A database stores each rocket engine’s propulsion type as a numeric code: 1 for solid, 2 or 3 for the two liquid-engine variants in use, and 4 for electric.
Write a MATLAB script that converts an engine’s code into a readable propulsion type.
Solution
Because codes 2 and 3 should both map to 'Liquid', we can group them into a single case instead of writing two separate cases with identical statements:
engine_code = 3;
switch engine_code
case 1
engine_type = 'Solid';
case {2, 3}
engine_type = 'Liquid';
case 4
engine_type = 'Electric';
otherwise
engine_type = 'Unknown';
end
disp(engine_type)
Liquid
Strings and Switch
switch also works on strings, comparing expression against each case value with the same rules as strcmp.
This comes up often when a variable represents a named mode or state rather than a number, for example:
switch flight_phase
case 'ascent'
disp('Throttle for max Q')
case 'coast'
disp('Engines off')
case 'descent'
disp('Prepare for landing')
end
Reading Questions
- When is a
switchstatement a better choice thanif-elseif? - Does MATLAB’s
switchstatement fall through to the next case after a match, like some other languages? - How would you write a single
casethat matches either the value5or the value10? - What does the
otherwiseblock do, and is it required? - Can a
switchstatement compare strings as well as numbers?