Bird
Raised Fist0
MATLABdata~10 mins

Switch-case statements in MATLAB - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Switch-case statements
Evaluate expression
↓
Compare with case 1
Yes / No↓
Run case 1
Yes / No↓
Run case 2
↓
Run default if no match
↓
End
The switch expression is evaluated once, then compared to each case in order. When a match is found, that case runs. If no match, the default runs.
Execution Sample
MATLAB
x = 2;
switch x
    case 1
        disp('One');
    case 2
        disp('Two');
    otherwise
        disp('Other');
end
This code checks the value of x and prints a message depending on which case matches.
Execution Table
StepExpression ValueCase ComparedMatch?ActionOutput
121NoCheck next case
222YesExecute case 2 blockTwo
32otherwiseSkippedSwitch ends
💡 Match found at case 2, so switch ends after executing case 2 block.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
x2222
Key Moments - 2 Insights
Why does the switch stop after executing case 2 and not check other cases?
In MATLAB switch-case, once a matching case is found and executed, the switch ends immediately as shown in execution_table step 2.
What happens if none of the cases match the expression value?
The 'otherwise' block runs if no case matches, as shown in the concept_flow and would appear in the execution_table if no matches occurred.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at step 2?
ATwo
BOne
COther
DNo output
💡 Hint
Check the 'Output' column in execution_table row for step 2.
At which step does the switch statement stop checking cases?
AStep 1
BStep 2
CStep 3
DIt checks all cases
💡 Hint
Look at the 'Match?' and 'Action' columns in execution_table to see when it stops.
If x was 5, which row in the execution table would show the executed case?
AStep 1
BStep 2
CStep 3
DNo row, switch ends immediately
💡 Hint
Refer to the 'otherwise' case in concept_flow and execution_table for no matches.
Concept Snapshot
switch expression
    case value1
        % code for value1
    case value2
        % code for value2
    otherwise
        % code if no case matches
end

- Expression evaluated once
- Runs first matching case
- 'otherwise' runs if no match
- Switch ends after one case runs
Full Transcript
This visual execution shows how MATLAB switch-case statements work. The expression is evaluated once. Each case is checked in order. If a case matches, its code runs and the switch ends immediately. If no case matches, the 'otherwise' block runs. The example uses x=2, so case 2 matches and prints 'Two'. Variables remain unchanged during the switch. Key points include that only one case runs and the switch stops after that. The quiz questions help check understanding of output, stopping point, and default case behavior.

Practice

(1/5)
1. What is the main purpose of a switch-case statement in MATLAB?
easy
A. To repeat a block of code multiple times
B. To create a new variable
C. To define a function
D. To execute different blocks of code based on the value of a variable

Solution

  1. Step 1: Understand the role of switch-case

    A switch-case statement chooses which code to run depending on a variable's value.
  2. Step 2: Compare with other options

    Repeating code is done by loops, defining functions is different, and creating variables is unrelated.
  3. Final Answer:

    To execute different blocks of code based on the value of a variable -> Option D
  4. Quick Check:

    Switch-case selects code by value [OK]
Hint: Switch-case runs code based on one variable's value [OK]
Common Mistakes:
  • Confusing switch-case with loops
  • Thinking switch-case defines functions
  • Assuming switch-case creates variables
2. Which of the following is the correct syntax to start a switch-case block in MATLAB?
easy
A. switch variable
B. case variable
C. switch-case(variable)
D. switch = variable

Solution

  1. Step 1: Recall switch-case syntax

    The switch statement starts with the keyword switch followed by the variable name.
  2. Step 2: Check each option

    switch variable matches correct syntax. Options A, B, and C are invalid MATLAB syntax for switch.
  3. Final Answer:

    switch variable -> Option A
  4. Quick Check:

    Start switch with 'switch variable' [OK]
Hint: Start switch with 'switch' plus variable name [OK]
Common Mistakes:
  • Using parentheses after switch
  • Writing 'case' instead of 'switch' to start
  • Assigning variable with '=' in switch
3. What will be the output of this MATLAB code?
color = 'green';
switch color
    case 'red'
        disp('Stop')
    case 'green'
        disp('Go')
    otherwise
        disp('Wait')
end
medium
A. Go
B. Wait
C. Stop
D. Error

Solution

  1. Step 1: Check the value of variable 'color'

    The variable color is set to 'green'.
  2. Step 2: Match the case in switch

    The switch checks cases: 'red' (no), 'green' (yes), so it runs disp('Go').
  3. Final Answer:

    Go -> Option A
  4. Quick Check:

    color='green' triggers 'Go' [OK]
Hint: Match variable value to case labels to find output [OK]
Common Mistakes:
  • Choosing output from wrong case
  • Ignoring the otherwise block
  • Assuming syntax error
4. Identify the error in this MATLAB switch-case code:
value = 10;
switch value
case 5
    disp('Five')
case 10
    disp('Ten')
case
    disp('Other')
end
medium
A. Incorrect variable name in switch
B. Missing 'otherwise' keyword for default case
C. Missing 'end' statement
D. Case values must be strings

Solution

  1. Step 1: Review the case statements

    The last case has no value and no keyword 'otherwise'. MATLAB requires 'otherwise' for default.
  2. Step 2: Check syntax rules

    Case values can be numbers, 'end' is present, variable name is correct.
  3. Final Answer:

    Missing 'otherwise' keyword for default case -> Option B
  4. Quick Check:

    Default case needs 'otherwise' keyword [OK]
Hint: Use 'otherwise' for default case, not empty case [OK]
Common Mistakes:
  • Leaving case without value or otherwise
  • Thinking 'end' is missing
  • Believing case values must be strings
5. You want to write a MATLAB switch-case that prints 'Weekend' for days 'Saturday' and 'Sunday', 'Weekday' for Monday to Friday, and 'Invalid' otherwise. Which code correctly implements this?
hard
A. switch day case ['Saturday', 'Sunday'] disp('Weekend') case ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] disp('Weekday') otherwise disp('Invalid') end
B. switch day case 'Saturday' || 'Sunday' disp('Weekend') case 'Monday' || 'Tuesday' || 'Wednesday' || 'Thursday' || 'Friday' disp('Weekday') otherwise disp('Invalid') end
C. switch day case {'Saturday', 'Sunday'} disp('Weekend') case {'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'} disp('Weekday') otherwise disp('Invalid') end
D. switch day case 'Saturday', 'Sunday' disp('Weekend') case 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday' disp('Weekday') otherwise disp('Invalid') end

Solution

  1. Step 1: Understand how to group cases in MATLAB

    MATLAB allows grouping multiple values in a cell array inside case, like {'Saturday', 'Sunday'}.
  2. Step 2: Check each option's syntax

    switch day case {'Saturday', 'Sunday'} disp('Weekend') case {'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'} disp('Weekday') otherwise disp('Invalid') end uses correct cell arrays for grouping. switch day case 'Saturday' || 'Sunday' disp('Weekend') case 'Monday' || 'Tuesday' || 'Wednesday' || 'Thursday' || 'Friday' disp('Weekday') otherwise disp('Invalid') end uses invalid '||' inside case. switch day case ['Saturday', 'Sunday'] disp('Weekend') case ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] disp('Weekday') otherwise disp('Invalid') end uses square brackets which is wrong for strings. switch day case 'Saturday', 'Sunday' disp('Weekend') case 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday' disp('Weekday') otherwise disp('Invalid') end uses commas incorrectly.
  3. Final Answer:

    Code with cell arrays for grouped cases -> Option C
  4. Quick Check:

    Group cases with cell arrays {} in switch-case [OK]
Hint: Group multiple cases using curly braces {} [OK]
Common Mistakes:
  • Using || inside case labels
  • Using square brackets for string groups
  • Separating cases with commas instead of cell arrays
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard