A switch statement compares a “switch” value to several alternate “case” values. If the switch value matches one of these case values, the associated statements will be executed. A switch or a case value should be a scalar or an array of characters.
For motivation, consider the following example. The switch statement here determines my phone's brand: Apple, Samsung, Nokia, or an unknown brand.
The value of myphone is compared to the case values one by one:
'apple'. 'apple', it compares with the next, which is 'samsung'. 'samsung', it tries 'nokia'. otherwise will be executed.myphone='apple';
switch myphone
case 'apple'
disp('It is an Apple phone')
case 'samsung'
disp('It is a Samsung phone')
case 'nokia'
disp('It is a nokia phone')
otherwise
disp('It is an unknown brand')
end
It is an Apple phone
Note that otherwise is not mandatory. You can omit otherwise if there is nothing to execute when the variable matches none of the case values.
The switch statement has the following syntax pattern:
switch expression
case expression_1
statements
case expression_2
statements
...
case expression_n
statements
otherwise
statements
end
expression and expression_1, expression_2, ..., expression_n should evaluate to a character array or a scalar. expression and expression_i evaluate to the same values, then the statements under expression_i will be executed. otherwise are executed. But, otherwise is not mandatory and can be skipped.| MATLAB | SIMO |
|---|---|
A case can be followed by a cell array. | Cell array not supported |
A case can be associated with multiple values by using a cell array | Only one value can be associated with a case since cell array is not supported |