| MATLAB Function Reference | ![]() |
根據表達格式(expression)來決定執行哪一個case(Switch among several cases based on expression)
Syntax
switchswitch_exprcasecase_exprstatement,...,statement case {case_expr1,case_expr2,case_expr3,...}statement,...,statement ... otherwise statement,...,statement end
Discussion
switch 語法是一種條件執行碼(conditionally executing code)。 switch
挑選多組指令中的其中一組來執行。每一組指令都叫做 case 。case包括:
在基本語法中, switch 執行和第一個case的關連式: switch_expr == case_expr.
(switch executes the statements associated with the first case where switch_expr == case_expr.)。當case表達格式(expressions)為細胞陣列(cell
array)時(如下面的第二個case),若細胞陣列(cell array)中的任何元素能和switch表達格式(expressions)相符, case_expr
就算符合。若沒有任何case表達格式(expression)和switch的表達格式(expression)相符,將會執行 otherwise
(若存在的話)。在case執行過後,程式將會從 end 之後繼續執行。
switch_expr 可以是數字或是字串。若為數字,當switch_expr==case_expr
成立即為switch_expr 符合 case_expr。若為字串,當strcmp(switch_expr,case_expr)回傳1(true)時即為switch_expr
符合 case_expr。
C
語言程式設計師注意 MATLAB的 switch 不像C語言的 switch
一樣,會「繼續往下執行」。也就是說 switch 只會執行第一個符合的case,而接下來就不會執行,所以不用 break
指令。
|
Examples
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
See Also
case, end, if, otherwise, while
| svds | symamd | ![]() |