Skip to main content
Contents
Calc
Dark Mode Prev Next Profile
\(\newcommand\DLGray{\color{Gray}}
\newcommand\DLO{\color{BurntOrange}}
\newcommand\DLRa{\color{WildStrawberry}}
\newcommand\DLGa{\color{Green}}
\newcommand\DLGb{\color{PineGreen}}
\newcommand\DLBa{\color{RoyalBlue}}
\newcommand\DLBb{\color{Cerulean}}
\newcommand\ds{\displaystyle}
\newcommand\ddx{\frac{d}{dx}}
\newcommand\os{\overset}
\newcommand\us{\underset}
\newcommand\ob{\overbrace}
\newcommand\obt{\overbracket}
\newcommand\ub{\underbrace}
\newcommand\ubt{\underbracket}
\newcommand\ul{\underline}
\newcommand\tikznode[3][]
{\tikz[remember picture,baseline=(#2.base)]
\node[minimum size=0pt,inner sep=0pt,#1](#2){#3};
}
\newcommand\del{\nabla}
\newcommand\R{\mathbb{R}}
\newcommand\C{\mathcal{C}}
\newcommand\N{\mathcal{N}}
\newcommand\eps{\varepsilon}
\renewcommand\epsilon{\varepsilon}
\renewcommand\subset{\subseteq}
\newcommand\norm[1]{\|{#1}\|}
\newcommand\matrixbrackets[4][1]{
\draw (#3,#2) -- (\fpeval{#3+0.2},#2);
\draw (#3,#1) -- (#3 ,#2);
\draw (#3,#1) -- (\fpeval{#3+0.2},#1);
\draw (#4,#2) -- (\fpeval{#4-0.2},#2);
\draw (#4,#1) -- (#4 ,#2);
\draw (#4,#1) -- (\fpeval{#4-0.2},#1);
}
\tikzstyle{circle node 0}=[fill=white, draw=black, shape=circle, inner sep=0pt]
\tikzstyle{circle node 2}=[fill=white, draw=black, shape=circle, inner sep=2pt]
\tikzstyle{hrect node}=[fill=white, draw=black, inner sep=2pt, outer sep=3pt]
\tikzstyle{vrect node}=[fill=white, draw=black, inner sep=0pt, outer sep=0pt]
\tikzstyle{hidden node 0}=[inner sep=0pt, outer sep=0pt]
\tikzstyle{hidden node 2}=[fill=white, inner sep=2pt, outer sep=2pt]
\tikzstyle{rect node 1}=[fill=white, inner sep=2pt, outer sep=0pt]
\tikzstyle{rect node 2}=[fill=white, draw=black, inner sep=2pt, outer sep=0pt]
\newcommand{\lt}{<}
\newcommand{\gt}{>}
\newcommand{\amp}{&}
\definecolor{fillinmathshade}{gray}{0.9}
\newcommand{\fillinmath}[1]{\mathchoice{\colorbox{fillinmathshade}{$\displaystyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\textstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptscriptstyle\phantom{\,#1\,}$}}}
\)
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.
π Like the if-statement, you can have as many branches as you like. You would just add additional
case statements between the
switch and
otherwise statements.
The switch Statement Structure.
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.
(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.
status = 'active';
switch status
case 'Active'
disp('User is active')
case 'active'
disp('User is online')
otherwise
disp('Unknown status')
end
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.