Strange behaviour of MATLAB find command

11 views (last 30 days)
avleed on 24 Jan 2017
Commented: Vald Bagina on 30 May 2020
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.

Accepted Answer

Stephen on 24 Jan 2017
Edited: Stephen on 24 Jan 2017
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)
>> fprintf('%.30f\n',g(27))
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
Vald Bagina
Vald Bagina on 30 May 2020
Thanks so much Stephen, I thought I might have had some floating point weirdness going here but your answer and PS. has helped me a lot. Cheers, that's made my afternoon.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!