ismember(a, b) function problem
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Akzeptierte Antwort
Voss
am 29 Mai 2022
Bearbeitet: Voss
am 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
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 Kommentare
Voss
am 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
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
Weitere Antworten (1)
Bjorn Gustavsson
am 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
0 Kommentare
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!