缩短MATLAB中具有大量'或'条件的'if'语句

use*_*243 1 matlab if-statement

假设我们if在MATLAB中有这个声明:

if rn == 1 || rn == 2 || rn == 3 || rn == 4 || rn == 5
  %% Some calculations
elseif rn == 6 || rn == 7 || rn == 8 || rn == 9 || rn == 10
  %% Some calculations
end
Run Code Online (Sandbox Code Playgroud)

有什么方法可以缩短这个if陈述吗?

hor*_*ler 7

您可以通过使用any检查值向量来执行此操作:

if any(rn == 1:5)
  %% Some calculations
else if any(rn == 6:10)
  %% Some calculations
end
Run Code Online (Sandbox Code Playgroud)