MATLAB: Indexing Issue (with both ismember() and find())

findfloating pointismemberlistMATLAB

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

Best Answer

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
See Floating-Point Numbers and colon for more informaiton.