ismember(a, b) function problem

7 vues (au cours des 30 derniers jours)
Jeffrey DG
Jeffrey DG le 29 Mai 2022
Commenté : Voss le 29 Mai 2022
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!

Réponse acceptée

Voss
Voss le 29 Mai 2022
Modifié(e) : Voss le 29 Mai 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
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 commentaires
Jeffrey DG
Jeffrey DG le 29 Mai 2022
Wow, thanks. I did not know you could also compare arrays just like that. You learn something new everyday!
Voss
Voss le 29 Mai 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
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.

Connectez-vous pour commenter.

Plus de réponses (1)

Bjorn Gustavsson
Bjorn Gustavsson le 29 Mai 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

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by