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.
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.
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
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
Line 1: The program takes a number as input.
Line 3: It passes to the switch statement.
Lines 4–9: The switch_expression
is being compared to the case_expressions
.
Lines 10–11: If the switch_expression
doesn't match case_expression
, we have an otherwise statement to execute.
Free Resources