Skip to content

MATLAB - Switch 语句

在 MATLAB 中,switch 语句提供了一种优雅的方式,根据单个变量或表达式的值,有条件地从多个选项中执行一个代码块。与冗长的 if-elseif-else 语句系列相比,它是一种更具可读性的替代方案,尤其是在处理可以取一系列离散、已知值的变量时。

switch 块会评估一个 switch_expression,然后将其值与每个 case 语句中的表达式进行比较。当找到匹配项时,MATLAB 会执行该 case 中的代码,然后退出 switch 块。如果没有 case 匹配,则执行可选的 otherwise 块。

如果满足以下条件之一,则 case 被视为匹配:

  • 对于数值类型,case_expression 等于 switch_expression(例如,5 == 5)。
  • 对于现代 string 数组(使用双引号),表达式相等(例如,"hello" == "hello")。
  • 对于传统字符向量(使用单引号),strcmp(case_expression, switch_expression) 返回 true。
  • 对于单元格数组 case_expression,单元格数组中至少有一个元素与 switch_expression 匹配。

otherwise 块是可选的,但强烈建议将其作为最佳实践,以处理意外值并防止错误。

MATLAB 中 switch 语句的基本语法是:

switch switch_expression
case case_expression_1
% 如果 switch_expression 匹配 case_expression_1 则执行的代码
statements_1
case case_expression_2
% 如果 switch_expression 匹配 case_expression_2 则执行的代码
statements_2
case {case_expression_3, case_expression_4} % 将多个 case 分组
% 当 case 3 或 case 4 匹配时执行的代码
statements_3_4
otherwise
% 如果没有其他 case 匹配则执行的代码
otherwise_statements
end

我们来创建一个现代示例,其中处理由 string 表示的用户命令。这种方法在交互式命令行工具中很常见。将以下代码保存到名为 processCommand.m 的文件中。

function processCommand(command)
% processCommand 使用 switch 语句处理命令字符串。
% 示例: processCommand("plot")
switch command
case "plot"
disp("Generating a sample plot...");
figure; % 创建一个新的图形窗口
plot(1:10, rand(1, 10));
title("Random Data Plot");
case {"list", "show"} % 使用单元格数组处理多个 case
disp("Listing available files:");
disp("- data.csv");
disp("- report.docx");
case "exit"
disp("Exiting application. Goodbye!");
otherwise
% 最佳实践是警告用户输入无效
warning('Invalid command: "%s". Type ''help processCommand'' for options.', command);
end
end

现在,从 MATLAB 命令行窗口使用不同的输入运行此函数:

processCommand("list")
Listing available files:
- data.csv
- report.docx
processCommand("plot")
Generating a sample plot...
% 将出现一个新的绘图窗口
processCommand("delete")
Warning: Invalid command: "delete". Type 'help processCommand' for options.
  • 始终包含 otherwise: 这使您的代码更健壮,通过优雅地处理意外值,而不是静默失败或稍后导致错误。
  • 使用 string 数组(双引号): 对于文本比较,现代 string 数组通常优于字符向量(单引号),因为它们的行为更直观。
  • 对常见 case 进行分组: 使用单元格数组 {} 将应执行相同代码的多个 case 分组。这避免了代码重复。
  • 避免过于复杂的逻辑: 如果您的条件涉及复杂的逻辑比较(>, <, &&, ||),则 if-elseif-else 结构通常更合适且更具可读性。