switch
塊有條件地執行來自多個選擇的一組語句。每個選擇由case
語句指定。
評估的switch_expression
是一個標量或字串。
評估的case_expression
是標量,標量或字串的字串或單元格數組。
switch
塊測試每種情況,直到其中一種情況為真(true
)。以下情況是真的 -
- 對於數字,
eq(case_expression,switch_expression)
。 - 對於字串,
strcmp(case_expression,switch_expression)
。 - 對於對象,支持
eq(case_expression,switch_expression)
。 - 對於單元格數組
case_expression
至少有一個。
當情況(case
)為真時,MATLAB會執行相應的語句,然後退出switch
塊。
otherwise
塊是可選的,並且僅在沒有case
為真時執行。
語法
MATLAB中switch
語句的語法是 -
switch <switch_expression>
case <case_expression>
<statements>
case <case_expression>
<statements>
...
...
otherwise
<statements>
end
例子
創建腳本檔並在其中鍵入以下代碼 -
grade = 'B';
switch(grade)
case 'A'
fprintf('Excellent!\n' );
case 'B'
fprintf('Well done\n' );
case 'C'
fprintf('Well done\n' );
case 'D'
fprintf('You passed\n' );
case 'F'
fprintf('Better try again\n' );
otherwise
fprintf('Invalid grade\n' );
end
執行上面示例代碼,得到以下結果 -
Well done