Indexing Issue (with both ismember() and find())
조회 수: 7 (최근 30일)
이전 댓글 표시
I have a really stange thing happening:
I have two arrays/lists that seem to match perfectly, but both the ismember function and the find function don't seem to recognize the third value...
array1 = [.1,.2,.3,.4];
array2 = [];
for i = .1:.1:.4
array2 = [array2, i];
end
array1
array2
ismember(array2,array1)
find(array2==array1)
These are the results:
array1 =
0.1000 0.2000 0.3000 0.4000
array2 =
0.1000 0.2000 0.3000 0.4000
ans =
1×4 logical array
1 1 0 1
ans =
1 2 4
You can see that the arrays match perfectly, but for some reason, it thinks the 3rd slot does not
(This came up while I was trying to write code for Euler's Formula)
Thank You
댓글 수: 1
Stephen23
2020년 7월 9일
편집: Stephen23
2020년 7월 9일
"I have a really stange thing happening"
Nothing strange is happening.
"I have two arrays/lists that seem to match perfectly..."
Did you check this by just looking at some approximation of the values displayed in the command window or by using an actual robust method of comparison e.g. by obtaining their HEX representations or by using num2strexact ?
"...but both the ismember function and the find function don't seem to recognize the third value"
Because the third value is NOT the same.
"You can see that the arrays match perfectly..."
No, I can see that the arrays do NOT match perfectly:
>> array1-array2
ans =
0 0 -5.5511e-17 0
"... but for some reason, it thinks the 3rd slot does not"
Because they are different:
>> num2strexact(array1(3))
ans =
0.299999999999999988897769753748434595763683319091796875
>> num2strexact(array2(3))
ans =
0.3000000000000000444089209850062616169452667236328125
You did not take into account that you generated those binary floating point numbers in two different ways and so their accumulated error can be expected to be different. Common behaviors of binary floating point numbers have been discussed thoroughly many times:
This is worth reading as well:
Checking for exact equivalence will not work, the correct approach is to comapre the absolute difference against a tolerance.
채택된 답변
Star Strider
2020년 7월 9일
You have encountered floating-point approximation error, and the way the colon operator works.
Try this:
array1 = [.1,.2,.3,.4];
array2 = [];
for i = .1:.1:.4
array2 = [array2, i];
end
array1
array2
CheckEqual = array1-array2
ismembertol(array2,array1, 1E-4) % Use Tolerances
find(abs(array2-array1)<1E-4) % Use Tolerances
댓글 수: 2
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!