MATLAB: Strange behaviour of MATLAB find command

faqfindfloating pointieee754no bug

Recently a lot of changes have happened on my computer and I have some issues with MATLAB. Now I use a local trial license and before I was on a local full license and before that was a floating license. I also have a new pc and lots of changes with the configuration etc. and because of this I am not able to track back to what the problem could be and ask for your help.
Some lines in old code have stopped working for reasons unknown.
I will give an example..
In the attached .mat file, there are 2 arrays, g and p. g is an array of 410 elements and p is a single element array = 2.6.
Two commands that should give the same result are
find(g==p); find(g==2.6);
but on my computer, they don’t. The second command returns 27, correctly and the first command returns an empty matrix.
I don’t know why, could it be the numeric settings on my laptop, like , and . for German and English.. Or if there is a difference between the way things are processed in the trial and full license.

Best Answer

This is not a strange behavior at all, it has nothing to do with find, and it has nothing to do with the changes on your computer. You are the millionth beginner to discover that two different values are not equal. It is not a bug. This behavior is expected when comparing floating point values which are not the same. You might think that they are the same, but that is irrelevant to your computer. Lets have a look in detail:
>> find(g==p)
ans = []
Why does find not find any identical values? Because there are no identical values. Lets have a look at the values that you think are the same:
>> fprintf('%.30f\n',p)
2.599999999999999644728632119950
>> fprintf('%.30f\n',g(27))
2.600000000000000088817841970013
Do these look the same to you? This is such a common topic that it has been discussed thousands of times before. Try searching this forum for "floating point equals", or start by reading these:
This is worth reading as well:
PS: the solution, as every of those links will tell you, is never compare for equality between floating point values, and always use a tolerance:
>> find(abs(g-p)<0.001)
ans = 27