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 strings,

`strcmp(`

.,`case_expression`

) == 1`switch_expression`

For objects that support the

`eq`

function,

.==`case_expression`

`switch_expression`

For a cell array

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

, as defined above for numbers, strings, 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 string. An evaluated

`case_expression`

The `otherwise`

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

Was this topic helpful?