jsh*_*hep 5 matlab conditional if-statement logical-operators
如果变量满足两个值中的一个,我试图触发一个条件.我知道我可以表达为:
if x == 5 || x == 6
execute code...
end
Run Code Online (Sandbox Code Playgroud)
但我想知道是否有一些更优雅的东西,如果x有一个长名称.就像是:
if x == {5, 6}
execute code...
end
Run Code Online (Sandbox Code Playgroud)
有人有主意吗?
确实有一种通用的方法.您可以使用该any函数来测试是否x等于数组的任何元素:
if any(x == [5, 6])
% execute code
end
Run Code Online (Sandbox Code Playgroud)
这适用于数值数组.如果您正在处理单元阵列,可以使用 ismember(感谢@ nilZ0r!)
choices = {'foo', 'bar', 'hello'};
x = 'hello';
if ismember(x, choices)
% execute code
end
Run Code Online (Sandbox Code Playgroud)
ismember 适用于数值和单元格数组(感谢@TasosPapastylianou).