新浪博客

matlab之switch用法 

2014-06-24 13:21阅读:
一 用途 用于变量的多分支选择问题
二 语法
switch-case-end
switch 变量
case 常量1
语句序列1;
case 常量2
语句序列2;
........
case 常量n
语句序列n;
otherwise
语句序列;
end
三 注意
1.otherwise 语句可选
2.找到匹配的case后,执行完就自动退出,不必像c语言一样,必须用break结束.



help switch
switch Switch among several cases based on expression.
The general form of the switch statement is:

switch switch_expr
CASE case_expr,
statement, ..., statement
CASE {case_expr1, case_expr2, case_expr3,...}
statement, ..., statement
...
OTHERWISE,
statement, ..., statement
END

The statements following the first CASE where the switch_expr matches
the case_expr are executed. 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 match the switch expression then the OTHERWISE
case is executed (if it exists). Only one CASE is executed and
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).

Only the statements between the matching CASE and the next CASE,
OTHERWISE, or END are executed. Unlike C, the switch statement
does not fall through (so BREAKs are unnecessary).

Example:

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

我的更多文章

下载客户端阅读体验更佳

APP专享