[TOC]

Switch

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:

Input
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
Output
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.

Syntax

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

Difference with MATLAB

MATLABSIMO
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 arrayOnly one value can be associated with a case since cell array is not supported