MATLAB Answers

Logical indexing of table failing

18 views (last 30 days)
Roberto Munoz
Roberto Munoz on 10 Apr 2021 at 11:14
Edited: Roberto Munoz on 11 Apr 2021 at 0:53
I have a table with a field called gProb. I'm trying to run the following logical indexing:
T.gProb == 0.35;
However the logical indexing returns no hits when I know for certain that gProb does equal 0.35 in a few rows.
I've tried using other indexing conditions for gProb and they all work except this magic number for some reason.
I'm sure there must be a simple explanation for this, but at the moment cannot see why.

Answers (1)

John D'Errico
John D'Errico on 10 Apr 2021 at 11:30
No. You do NOT know it contains 0.35. In fact, MATLAB cannot represent 0.35 exactly in floating point arithmetic. This is for the same reason you cannot represent the fraction 1/3 as a finite decimal number.
So what you have there is APPROXIMATELY 0.35, created in that table in some way that we don't know. And then you are comparing that number to this:
sprintf('%0.55f',0.35)
ans = '0.3499999999999999777955395074968691915273666381835937500'
When MATLAB stores the number 0.35 as a double, it actually stores a 52 binary bit approximation to 0.35. In terms of a decimal number, that value is seen above.
NEVER trust the least significant bits of a floating point number. At least not until you truly understand floating point arithmetic, and you then undertand why and when you can trust a number. Learn to use tolerances if you don't know the value.
  1 Comment
Roberto Munoz
Roberto Munoz on 11 Apr 2021 at 0:47
I understand that matlab cannot represent 0.35 exactly in floating point arithmetic.
My question is why is the logical indexing failing when I have written the value 0.35 to some table rows.
What I have done is the following:
T.gProb(1:10) = 0.35;
rows = T.gProb == 0.35;
One would expect rows to return logical 1 in indices 1:10, however in my case it is not.
If its truly down to floating point arithmetic appriximations then so be it, but I find it very strange and unusual that MATLABs implementation of logical indexing would produce unexpected results in this simple application.
So I posit that I'm doing something erroneous rather than the program.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by