array indexing returns empty row vector while attempting to locate index corresponding to only certain array values
7 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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)
However, the correct index is returned for all other values of h. For example:
index(h==0.2)
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.
0 commentaires
Réponse acceptée
Dave B
le 14 Sep 2021
This is an issue of floating point arithmetic, another way to state the problem is:
(.1+.2)==.3
What? How can those not be equal? Actually they're really close:
(.1+.2) - .3
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)
2 commentaires
Dave B
le 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!
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!