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

조회 수: 7 (최근 30일)
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.

채택된 답변

Dave B
Dave B 2021년 9월 14일
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
Aaron Annan
Aaron Annan 2021년 9월 16일
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 2021년 9월 16일
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!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by