MATLAB Function Reference
  Go to function:
    Search    Help Desk 
switch    Examples   See Also

Switch among several cases based on a conditional expression

Syntax

Description

The switch statement syntax is a means of conditionally executing code. In particular, switch executes one set of statements selected from an arbitrary number of alternatives, called case groups. Each case group consists of:

Execution of the switch statement begins with an evaluation of switch_expr. The determined value is then compared to each case_expr in the order in which they appear in the switch statement. The statements associated with the first case where switch_expr matches case_expr are executed.

A cell array can be used to associate a list of case expressions with a set of statements. The cell array syntax is shown in the second case group above. A match of the switch_expr with any element in the cell array will result in a match to the case group.

The switch_expr can be a scalar or a string. A scalar switch_expr matches a case_expr if switch_expr == case_expr. A string switch_expr matches a case_expr if strcmp(switch_expr,case_expr) returns 1 (true).

If switch_expr does not match the case expression for any of the case groups, control is passed to the optional otherwise case. The otherwise statement does not include any conditional expressions and therefore matches all values of switch_expr.

After executing the appropriate case or otherwise group, program execution continues with the statement after the end statement.

Note for C Programmers:
The MATLAB switch construct is different from the C programming language switch construct. The C switch construct allows execution to "fall through" many case groups before ending, using break statements to control execution. The MATLAB switch construct executes one case group at most and therefore break statements are not required.

Examples

Assume method exists as a string variable:

See Also

case, end, if, otherwise, while



[ Previous | Help Desk | Next ]