Skip to main content
Logo image

Subsection Switch Statement

The switch statement is another option for controlling flow in MATLAB. It is best when you are comparing one value to a list of discrete, exact matches.
A switch statement compares a variable to the values listed in each case. The first match runs, and MATLAB skips the rest.

πŸ“

The switch Statement Structure.

Use Case:
  • if var is equal to val1, run blockA,
  • if var is equal to val2 or val3, run blockB,
  • if var is equal to val4, run blockC,
  • if var was not matched, run blockD (default).
switch var

	case val1          % var == val1? YES ➜ run blockA 
		               %              NO  ➜ check next case
		blockA
	case {val2, val3}  % var == val2 OR val3? Yes ➜ run blockB
		               %                      NO  ➜ check next case
		blockB
	case val4          % var == val4? Yes ➜ run blockC
		               %              NO  ➜ check next case
		blockC
	otherwise          % no matches? YES ➜ run blockD
		               %             NO  ➜ check next case
		blockD
end
Rules:
  • Case values are checked in order from top to bottom.
  • The otherwise block runs only when no cases match.
  • The otherwise (default) branch is optional.
  • When there is only one case value, curly braces { } are optional.
  • Every switch-statement must end with end.
  • Case values can be numbers, strings, or other data types that support equality comparisons.
  • Case values are case-sensitive when comparing strings.
  • Case values must be unique; duplicate case values will cause an error.
Limitations:
  • Case values cannot use logical operators (e.g., <, >, ==, &, |).
  • Switch statements are not suitable for range-based conditions (e.g., checking if a value is between two numbers).
The switch-case structure is similar to the if structure, but offers a few advantages. First, it is easier to read; second, it is better when comparing strings (of possibly different lengths).
As an example, let’s check whether a cadet is in their first two years at VMI.
The cases are grouped by curly brackets so that a case will be satisfied if the value of Year is any of the values in a specific case. Once this code is executed, the switch command will attempt to match value of Year.

Checkpoint 30.

(a)

(i) Switch keywords and roles.
    Match each switch keyword to its role.
    A switch block tests one expression, each case provides a value to match, and otherwise provides the default path before end closes the block.
  • switch
  • Starts the block and names the expression to compare.
  • case
  • Runs when the expression matches a listed value.
  • otherwise
  • Runs when no case matches.
  • end
  • Closes the switch statement.

(b) Switch vs if-elseif for exact matches.

When is a switch statement more suitable than an if-elseif-else chain? Select all that apply.
  • When comparing a single variable to multiple exact values.
  • The switch statement is designed for testing one variable against a list of specific values.
  • When you need to test ranges like x > 10.
  • Switch statements cannot use logical operators or ranges; use if-elseif for range-based conditions.
  • When comparing string values of different lengths.
  • Switch statements handle string comparisons cleanly, especially when strings have different lengths.
  • When the case values need to be computed at runtime.
  • Case values must be hard-coded constants, not variables or expressions.

(c) Otherwise branch is optional in switch.

    The otherwise branch in a switch statement is optional.
  • True.

  • While the otherwise branch is optional, including it provides a default action when no cases match, which can help prevent unintended behavior.
  • False.

  • While the otherwise branch is optional, including it provides a default action when no cases match, which can help prevent unintended behavior.

πŸ§‘πŸ»β€πŸ’» Class Activities πŸ§‘πŸ»β€πŸ’» Class Activities

These in-class activities focus on writing small MATLAB functions that use if and switch statements. Each activity includes multiple parts and asks you to reason about which branch executes.

1. Shipping Mode Switch.

Use a switch statement to choose among discrete shipping options.
(a)
Create a function named shipping_cost that takes a mode input ('S', 'E', or 'O') and returns a scalar cost of 5, 12, or 20.
Solution.
function cost = shipping_cost(mode)
	switch mode
		case 'S'
			cost = 5;
		case 'E'
			cost = 12;
		case 'O'
			cost = 20;
		otherwise
			cost = NaN;
	end
end
(b)
Extend the function so it also accepts full words ('standard', 'express', and 'overnight') in addition to the single-letter codes.
Solution.
function cost = shipping_cost(mode)
	switch mode
		case {'S', 'standard'}
			cost = 5;
		case {'E', 'express'}
			cost = 12;
		case {'O', 'overnight'}
			cost = 20;
		otherwise
			cost = NaN;
	end
end
(c)
Concept check: what happens when mode = 'e' (lowercase), and why?
Solution.
The otherwise branch runs and returns NaN because switch comparisons are case-sensitive, so 'e' does not match 'E'.

2. Day Type Switch.

Map a day number to weekday or weekend status using a switch-statement.
(a)
Write a function named day_type that takes an integer dayNum (1 = Monday, 7 = Sunday). Return 'weekday' for 1--5 and 'weekend' for 6--7.
(b)
Update the function to return a second output named isWeekend that is true or false for valid days.
(c)
Concept check: what should the function return for dayNum = 0, and which branch handles it?

3. Thermostat Mode Switch.

Use a discrete numeric code to select a thermostat mode.
(a)
Create a function named thermostat_mode that takes a numeric code: 0 for off, 1 for heat, and 2 for cool. Return the string 'off', 'heat', or 'cool'.
(b)
Extend the function to return a second output setPoint. Use 68 for heat, 74 for cool, and NaN for off or invalid codes.

Exercises πŸ€”πŸ’­ Conceptual Questions

1.

(a) Switch Case Values.
Which of the following statements about switch case values are true? Select all that apply.
  • The otherwise block is optional.
  • In a switch statement the otherwise block is optional.
  • Case values can be numbers.
  • Correct! Switch cases can match numeric values.
  • Case values can be strings.
  • Correct! Switch cases work well with string comparisons.
  • Case values can use relational operators like > or <.
  • Incorrect. Switch statements only test for equality. Use if-elseif for range-based conditions.
  • Multiple case values can be grouped using curly braces { }.
  • Correct! You can use case {val1, val2, val3} to match multiple values.
(b) Otherwise Branch Behavior.
    In a switch statement, the otherwise block only runs when none of the case values match.
  • True.

  • Correct! The otherwise branch is similar to the else in an if statementβ€”it provides a default action when no cases match.
  • False.

  • Correct! The otherwise branch is similar to the else in an if statementβ€”it provides a default action when no cases match.
(c) Switch Case Sensitivity.
Consider this code:
status = 'active';
switch status
	case 'Active'
		disp('User is active')
	case 'active'
		disp('User is online')
	otherwise
		disp('Unknown status')
end
What will be displayed?
  • User is active
  • Incorrect. Case values are case-sensitive, so 'Active' does not match 'active'.
  • User is online
  • Correct! The string 'active' exactly matches the second case. Switch comparisons are case-sensitive.
  • Unknown status
  • Incorrect. There is a case that matches: the second case 'active'.
  • An error will occur.
  • Incorrect. This is valid code; the second case matches and executes.
(d) When to Use Switch vs If.
Which scenario is best suited for a switch statement rather than an if-elseif chain?
  • Comparing a variable to a list of specific string values.
  • Correct! Switch statements are ideal for testing exact matches against discrete values, especially strings.
  • Checking if a number falls within different ranges (e.g., 0-10, 10-20).
  • Incorrect. Range-based conditions require relational operators like > or <=, which switch statements cannot handle. Use if-elseif instead.
  • Testing multiple logical conditions that use AND (&) or OR (|).
  • Incorrect. Switch statements only test for equality. Use if-elseif for complex logical conditions.
  • Checking if a value is greater than a threshold.
  • Incorrect. This requires a relational operator (>), which switch statements cannot use. Use an if statement.
(e) Duplicate Case Values.
What happens if a switch statement contains duplicate case values?
  • MATLAB runs both matching cases.
  • Incorrect. MATLAB will actually report an error if you try to use duplicate case values.
  • MATLAB runs the first matching case and ignores the duplicate.
  • Incorrect. MATLAB doesn’t allow duplicate case values at all.
  • MATLAB uses the last duplicate case value.
  • Incorrect. MATLAB won’t allow duplicate case values at all.
  • MATLAB produces an error.
  • Correct! Duplicate case values are not allowed in MATLAB switch statements and will cause an error.