How to use the switch command in MATLAB
What is a switch command?
The switch command executes a group of several statements where it checks n number of cases that follows the switch command, and if they don't match, it executes the command followed by otherwise.
Explanation
The illustration above explains the working of the switch statement. The program enters the switch statement, which forwards it to the cases; if the switch_expression matches the cases_expression, it executes that case statement. If none of the case expressions matches, it will execute the otherwise statement irrespective of the original statement. A case expression will be valid as follows:
If the expression takes a number,
case_expression==switch_expression.If it takes characters, strcmp(
case_expression,switch_expression) == 1.If it takes objects that support the eq function,
case_expression==switch_expression.If it takes a cell array, one element of case expression should match the switch expression, as it is defined for all kinds above.
Syntax
The syntax for switch, case, and otherwise in Matlab is in the code widget below, which matches the illustration attached above.
switch switch_expressioncase case_expressionstatementscase case_expressionstatements...otherwisestatementsend
Program
In the code widget below, we have a set of switch, case, and otherwise statements.
n = input('Enter a number: ');switch ncase -1disp('negative one')case 0disp('zero')case 1disp('positive one')otherwisedisp('other value')end
Explanation
Line 1: The program takes a number as input.
Line 3: It passes to the switch statement.
Lines 4–9: The
switch_expressionis being compared to thecase_expressions.Lines 10–11: If the
switch_expressiondoesn't matchcase_expression, we have an otherwise statement to execute.
Free Resources