如何在一个等价语句中包含多个条件?

How to include multiple conditions in one equivalence statement?

我试图在变量满足两个值之一时触发条件。我知道我可以将其表达为:

if x == 5 || x == 6
    execute code...
end

但我想知道如果 x 的名字很长,是否有更优雅的东西。类似于:

if x == {5, 6}
    execute code...
end

有人有什么想法吗?

确实有一个通用的方法。您可以使用 any 函数来测试 x 是否等于数组的任何元素:

if any(x == [5, 6])
    % execute code
end

这适用于数值数组。如果你正在处理元胞数组,你可以使用 ismember(感谢 @ nilZ0r!)

choices = {'foo', 'bar', 'hello'};
x = 'hello';

if ismember(x, choices)
    % execute code
end

ismember 适用于数值数组和元胞数组(感谢@TasosPapastylianou)。

switch-case 环境是一个不错的选择:

switch x
    case {5,6}
        x.^2
    case {7,8}
        x.^4
    otherwise
        x.^3
end

也适用于字符串:

switch x
    case {'foo','bar'}
        disp(x)
    otherwise
        disp('fail.')
end