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

Switch among several cases based on expression

Syntax

Discussion

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. Each alternative is called a case, and consists of:

In its most basic syntax, switch executes only the statements associated with the first case where switch_expr == case_expr. When the case expression is a cell array (as in the second case above), the case_expr matches if any of the elements of the cell array match the switch expression.If none of the case expressions matches the switch expression, then control passes to the otherwise case (if it exists). Only one case is executed, and program execution resumes with the statement after the end.

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).

Examples

Assume method exists as a string variable:

See Also

case, end, if, otherwise, while



[ Previous | Help Desk | Next ]