array indexing returns empty row vector while attempting to locate index corresponding to only certain array values
7 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Aaron Annan
el 14 de Sept. de 2021
Comentada: Dave B
el 16 de Sept. de 2021
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 comentarios
Respuesta aceptada
Dave B
el 14 de Sept. de 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 comentarios
Dave B
el 16 de Sept. de 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!
Más respuestas (0)
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!