ismember(a, b) function problem

조회 수: 5 (최근 30일)
Jeffrey DG
Jeffrey DG 2022년 5월 29일
댓글: Voss 2022년 5월 29일
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