如果变量满足两个值中的一个,我试图触发条件。我知道我可以表达为:
if x == 5 || x == 6
execute code...
end
但我想知道如果x
有一个很长的名字,是否有更优雅的东西。类似的东西:
if x == {5, 6}
execute code...
end
有人有什么想法吗?
答案 0 :(得分:6)
确实存在一般方法。您可以使用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)。
答案 1 :(得分:3)
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