如果数组的元素b=[1,2,3,4,5]
等于 1 或 2 或 5,我想返回 true。我该怎么做?
2 回答
There are different ways to do that:
Test an individual element against one number
b(1) == 5
Test an individual element against several numbers, i.e. is the first element either 1 or 2 or 5?
b(1) == 1 || b(1) == 2 || b(1) == 5
%# which is equivalent to
any(b(1) == [1 2 5];
Test all (or many) elements against one number
b == 1; %# a vector with t/f for each element
Test all elements against several numbers
b == 1 | b == 2 | b == 5 %# note that I can't use the shortcut ||
%# this is equivalent to
ismember(b,[1 2 5])
这很简单。要测试数字的相等性,您只需使用==
运算符。
if (b(1) == 5)
%% first element of b is 5
%% now implement code you require
同样,您可以测试矩阵中任何元素的相等性。要测试多个值,请使用逻辑或运算符||
,==
例如
if (b(1) == 5 || b(1) == 2 || b(1) == 1)
%% first element of b is 1,2 or 5
%% now implement code you require