Main Content

Execute one of several groups of statements

switchcase`switch_expression`

`case_expression`

case`statements`

`case_expression`

... otherwise`statements`

end`statements`

`switch `

evaluates
an expression and chooses to execute one of several groups of statements.
Each choice is a case. * switch_expression*,
case

`case_expression`

The `switch`

block tests each case until one
of the case expressions is true. A case is true when:

For numbers,

.==`case_expression`

`switch_expression`

For character vectors,

`strcmp(`

.,`case_expression`

) == 1`switch_expression`

For objects that support the

`eq`

function,

. The output of the overloaded==`case_expression`

`switch_expression`

`eq`

function must be either a logical value or convertible to a logical value.For a cell array

, at least one of the elements of the cell array matches`case_expression`

, as defined above for numbers, character vectors, and objects.`switch_expression`

When a case expression is true, MATLAB^{®} executes the corresponding
statements and exits the `switch`

block.

An evaluated * switch_expression* must
be a scalar or character vector. An evaluated

`case_expression`

The `otherwise`

block is optional. MATLAB executes
the statements only when no case is true.

A

cannot include relational operators such as`case_expression`

`<`

or`>`

for comparison against the. To test for inequality, use`switch_expression`

`if, elseif, else`

statements.The MATLAB

`switch`

statement does not fall through like a C language`switch`

statement. If the first`case`

statement is`true`

, MATLAB does not execute the other`case`

statements. For example:result = 52; switch(result) case 52 disp('result is 52') case {52, 78} disp('result is 52 or 78') end

result is 52

Define all variables necessary for code in a particular case within that case. Since MATLAB executes only one case of any

`switch`

statement, variables defined within one case are not available for other cases. For example, if your current workspace does not contain a variable`x`

, only cases that define`x`

can use it:switch choice case 1 x = -pi:0.01:pi; case 2 % does not know anything about x end

The MATLAB

`break`

statement ends execution of a`for`

or`while`

loop, but does not end execution of a`switch`

statement. This behavior is different than the behavior of`break`

and`switch`

in C.