目录

switch statement

切换块有条件地从多个选项中执行一组语句。 案例陈述涵盖了每种选择。

评估的switch_expression是标量或字符串。

评估的case_expression是标量,字符串或标量或字符串的单元格数组。

开关模块测试每种情况,直到其中一种情况为真。 一个案例是真的 -

  • 对于数字, eq(case_expression,switch_expression)

  • 对于字符串, strcmp(case_expression,switch_expression)

  • 对于支持eq(case_expression,switch_expression)对象eq(case_expression,switch_expression)

  • 对于单元阵列case_expression,单元阵列的至少一个元素与switch_expression匹配,如上面针对数字,字符串和对象所定义的。

当一个case为真时,MATLAB执行相应的语句,然后退出switch块。

otherwise块是可选的,仅在没有大小写时才执行。

语法 (Syntax)

MATLAB中switch语句的语法是 -

switch <switch_expression>
   case <case_expression>
      <statements>
   case <case_expression>
      <statements>
      ...
      ...
   otherwise
      <statements>
end

例子 (Example)

创建一个脚本文件并在其中键入以下代码 -

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
↑回到顶部↑
WIKI教程 @2018