array indexing returns empty row vector while attempting to locate index corresponding to only certain array values

7 views (last 30 days)
An array (h) is defined:
h = 0.1:0.05:0.5;
while a separate array (index) is used to store corresponding indices to members of h:
index = 1:length(h);
While attempting to use array indexing to get index (of index) corresponding to h = 0.3, the return is a 1X0 empty double row vector. This similarly occurs when h = 0.15, 0.175, and 0.325 (within the domain of h).
index(h==0.3)
ans = 1×0 empty double row vector
However, the correct index is returned for all other values of h. For example:
index(h==0.2)
ans = 3
Is there a reason why MATLAB would return an empty double row vector for the particular values as shown above?
The same problem exists for me using two independent machines (both Windows 64, one R2019b and other R2020b), and similar results occurred using the "RUN" feature of this thread while I was writing the description. Any help is greatly appreciated.

Accepted Answer

Dave B
Dave B on 14 Sep 2021
This is an issue of floating point arithmetic, another way to state the problem is:
(.1+.2)==.3
ans = logical
0
What? How can those not be equal? Actually they're really close:
(.1+.2) - .3
ans = 5.5511e-17
There are lots of threads about this on MATLAB Answers, this one is a good starter that links to more:
A (I know unsatisfying) answer may be to replace your == with a tolerance check:
h = 0.1:0.05:0.5;
index = 1:length(h);
tol = 1e-10;
index(abs(h-0.3) < tol)
ans = 5
  2 Comments
Aaron Annan
Aaron Annan on 16 Sep 2021
Thanks a lot Dave, the tolerance check fit my purposes. Forgive me for adding one more version of the recurring floating point error question to MATLAB central. The additional links you provided on that subject were also very helpful. Cheers.
Dave B
Dave B on 16 Sep 2021
No worries Aaron, one of the reasons this one comes up so much is that it's not intuitive (if you don't spend your days thinking about this kind of thing) and it's not totally obvious what to search for when you run into it!

Sign in to comment.

More Answers (0)

Tags

Products

Community Treasure Hunt

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

Start Hunting!