ismember(a, b) function problem
3 views (last 30 days)
Show older comments
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!
0 Comments
Accepted Answer
Voss
on 29 May 2022
Edited: Voss
on 29 May 2022
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
With your a and b:
a = [1, 1, 0];
b = [0, 1, 0];
logic = ismember(a,b)
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
2 Comments
Voss
on 29 May 2022
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
x = [1 2 3 4]; % 1-by-4 array
y = 2; % scalar
x == y % compares each element of x to y
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)
x = [1 2 3 4]; % 1-by-4 array
y = [2 5 8]; % 1-by-3 array
x == y % error
More Answers (1)
Bjorn Gustavsson
on 29 May 2022
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
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!