0
0
MatlabHow-ToBeginner ยท 3 min read

How to Use Switch Case in MATLAB: Syntax and Examples

In MATLAB, use the switch statement to execute different code blocks based on the value of a variable. The syntax includes switch, multiple case labels, and an optional otherwise block for unmatched cases.
๐Ÿ“

Syntax

The switch statement evaluates an expression once and compares it to each case value. If a match is found, MATLAB executes the corresponding code block. If no match is found, the otherwise block runs if it exists.

  • switch expression: The value to test.
  • case value: Possible values to match against the expression.
  • otherwise: Optional block executed if no case matches.
  • end: Ends the switch statement.
matlab
switch expression
    case value1
        % Code to execute if expression == value1
    case value2
        % Code to execute if expression == value2
    otherwise
        % Code to execute if no cases match
end
๐Ÿ’ป

Example

This example shows how to use switch to print a message based on a day of the week.

matlab
day = 'Tuesday';
switch day
    case 'Monday'
        disp('Start of the work week.');
    case 'Tuesday'
        disp('Second day of the work week.');
    case 'Friday'
        disp('Almost weekend!');
    otherwise
        disp('Just another day.');
end
Output
Second day of the work week.
โš ๏ธ

Common Pitfalls

Common mistakes when using switch in MATLAB include:

  • Not using end to close the switch block.
  • Using incompatible data types for case values (e.g., mixing strings and numbers).
  • Forgetting the otherwise block when needed to handle unexpected values.
  • Case values must be constant expressions, not variables or expressions.
matlab
%% Wrong: Missing end
switch x
    case 1
        disp('One')
    case 2
        disp('Two')
% Missing end here causes error

%% Right: Proper end
switch x
    case 1
        disp('One')
    case 2
        disp('Two')
end
๐Ÿ“Š

Quick Reference

KeywordDescription
switchStarts the switch-case block and evaluates the expression
caseDefines a value to compare with the expression
otherwiseOptional block executed if no case matches
endEnds the switch-case block
โœ…

Key Takeaways

Use switch to select code blocks based on a variable's value.
Always close the switch block with end.
Use otherwise to handle unexpected cases.
Case values must be constants, not variables or expressions.
Ensure data types of expression and case values match for correct comparison.