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
endto close the switch block. - Using incompatible data types for
casevalues (e.g., mixing strings and numbers). - Forgetting the
otherwiseblock 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
| Keyword | Description |
|---|---|
| switch | Starts the switch-case block and evaluates the expression |
| case | Defines a value to compare with the expression |
| otherwise | Optional block executed if no case matches |
| end | Ends 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.