| MATLAB Function Reference | Search  Help Desk |
| switch | Examples See Also |
Switch among several cases based on a conditional expression
Syntax
switchswitch_exprcasecase_exprstatementscase {case_expr1,case_expr2,case_expr3,...}statements... otherwisestatementsend
Description
Theswitch 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:
case statement, consisting of a case label and one or more conditional expressions
statements, where a statement can be another switch statement
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:
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
Assumemethod exists as a string variable:
switch lower(method)case {'linear','bilinear'}disp('Method is linear')case 'cubic'disp('Method is cubic')case 'nearest'disp('Method is nearest')otherwisedisp('Unknown method.')end
See Also
case, end, if, otherwise, while