find() doesn't work until viewing variable.

I'm trying to use the find function to find rows of my matrix containing 0.22, however it returns an empty matrix (even though it does contain 0.22 in multiple places).
>>find(nodes(:,2) == 0.22)
ans =
Empty matrix: 0-by-1
Strangley, if I open the matrix in the variable window, and click on the cell equal to 0.22, then click off it, then run the command again I get:
>> find(nodes(:,2) == 0.22)
ans =
11
Where 11 corresponds to the row of the cell I clicked. I'm almost certain the cell is exactly 0.22 (and it must be for the second command above to work), and I've also tried "==22*0.01" as was suggested on another answer, but this doesn't help.
Any suggestions as to why this is happening? I don't see how double clicking a value in the variable viewer could change its behavior with the find() command.

 Risposta accettata

Stephen23
Stephen23 il 13 Apr 2016
Modificato: Stephen23 il 13 Apr 2016
"I'm almost certain the cell is exactly 0.22"
No it isn't. And that is likely part of the problem.
I can't explain why it changes after clicking on the variable viewer, but there are more important issues at stake...
Although beginners often think that computers have infinite storage and precision, in reality they do not, and MATLAB (and lots of other tools other tools) uses IEEE 754 floating point numbers, which are stored in memory with fixed precision binary numbers. But finite precision binary numbers are not the same as finite precision decimal values.
Simply put, the value 0.22 cannot be stored exactly by any of the floating point numbers format that MATLAb uses (the default is double). Lets have a look at more digits of that number:
>> sprintf('%.30f',0.22)
ans = 0.220000000000000001110223024625
Why is this important? Because different ways of calculating, storing and processing numbers can give slightly different values, although you will not see this in the numbers that are displayed in the command window or variable viewer:
>> x = 0.22+eps/2, sprintf('%.30f',x)
x = 0.22000
ans = 0.220000000000000112132525487141
This is normal, and is the expected behavior of floating point numbers. Note that calculations on these numbers also operate on these digits, even if you can't see them! Why is this important? Because it means that you should never test for equality of floating point numbers. You should always use a tolerance value, and pick the tolerance to suit the magnitude of your data.
This is such a common topic you will find lots of help on this forum:

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by