find function cannot find the value
54 views (last 30 days)
Show older comments
Hello, I'm trying to use find function to find the value for example from a data with: data = [0, 1.00 2.00 3.00 4.00]; float values for example, if I do:
[~,indx] = find(data == 1.00),
the result would be an empty cell, []. Why is this the problem?
2 Comments
Stephen23
on 27 Sep 2017
This has been clearly explained hundreds of times before, e.g. from https://www.mathworks.com/matlabcentral/answers/321709-strange-behaviour-of-matlab-find-command:
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
Accepted Answer
Image Analyst
on 27 Sep 2017
It works fine:
data = [0, 1.00 2.00 3.00 4.00];
[~,indx] = find(data == 1.00)
In the command window:
indx =
2
I suspect your numbers aren't EXACTLY that and what you're running into is this: http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F
3 Comments
Walter Roberson
on 28 Sep 2017
There is no way to "fix" this for find() because it is not a find() issue.
You could consider using ismembertol()
More Answers (0)
See Also
Categories
Find more on Sparse Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!