ismember(a, b) function problem

5 次查看(过去 30 天)
Hello,
In brief, I am trying to compare two seperate arrays that decrease/increase till they are equal one another.
a = [1, 1, 0];
b = [0, 1, 0];
logic = ismember(a, b); % or ismembertol(a, b, 0.001);
if all(logic(:))
% Do somthing
end
However, I seem to be getting all true, [1, 1, 1], when I expect a [0, 1, 1] for this particular set of logical comaprison using ismember(). I am not good at coding so will appreciate if anyone could explain why this is happening.
Thank you!

采纳的回答

Voss
Voss 2022-5-29
编辑:Voss 2022-5-29
ismember(a,b) tells you whether each element of a exists somewhere in b
ismember([1 2 3 4 5],[2 4 6]) % 2 and 4 exist in [2 4 6], but 1, 3, and 5 do not
ans = 1×5 logical array
0 1 0 1 0
With your a and b:
a = [1, 1, 0];
b = [0, 1, 0];
logic = ismember(a,b)
ans = 1×3 logical array
1 1 1
you get logic is all true because all elements of a (i.e., 0 and 1) appear in b.
It seems that you actually want to compare each element of a and b, which you can do using ==
logic = a == b
logic = 1×3 logical array
0 1 1
  2 个评论
Jeffrey DG
Jeffrey DG 2022-5-29
Wow, thanks. I did not know you could also compare arrays just like that. You learn something new everyday!
Voss
Voss 2022-5-29
You're welcome!
FYI, here are some examples of using == with arrays:
x = [1 2 3 4]; % 1-by-4 array
y = [1 2 1 2]; % 1-by-4 array
x == y % compares each element of x to corresponding element of y
ans = 1×4 logical array
1 1 0 0
x = [1 2 3 4]; % 1-by-4 array
y = 2; % scalar
x == y % compares each element of x to y
ans = 1×4 logical array
0 1 0 0
x = [1 2 3 4]; % 1-by-4 array (row vector)
y = [2; 3; 5]; % 3-by-1 array (column vector)
x == y % also works! (compares each element of x to every element of y)
ans = 3×4 logical array
0 1 0 0 0 0 1 0 0 0 0 0
x = [1 2 3 4]; % 1-by-4 array
y = [2 5 8]; % 1-by-3 array
x == y % error
Arrays have incompatible sizes for this operation.

请先登录,再进行评论。

更多回答(1 个)

Bjorn Gustavsson
Bjorn Gustavsson 2022-5-29
The ismember function checks if elements in a are found in b, not that each element match. In your case both "1" in a have a value found in b and the same is true for the "0". Maybe you want your conditional to be:
if all(a==b)
% Do somthing
end
or perhaps
your_tol = 0.01;
if all(abs(a-b)<=your_tol)
% Do somthing
end
HTH

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

产品


版本

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by