MATLAB Function Reference |
Switch among several cases, based on expression
Syntax
switchswitch_expr
casecase_expr
statement, ..., statement case {case_expr1
,case_expr2
,case_expr3
, ...} statement, ..., statement otherwise statement, ..., statement end
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 basic syntax, switch
executes 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 matches the switch expression. If no case expression matches the switch expression, then control passes to the otherwise
case (if it exists). After the case is executed, 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 logical 1
(true
).
Examples
To execute a certain block of code based on what the string, method
, is set to,
method = 'Bilinear'; switch lower(method) case {'linear','bilinear'} disp('Method is linear') case 'cubic' disp('Method is cubic') case 'nearest' disp('Method is nearest') otherwise disp('Unknown method.') end Method is linear
See Also
case
, otherwise
, end
, if
, else
, elseif
, while
svds | symamd |
© 1994-2005 The MathWorks, Inc.