Violation of logical indexing criteria problem
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Sudipta Ray
le 20 Jan 2016
Commenté : Steven Lord
le 21 Jan 2016
Hi everyone. I am collecting grid points (alpha) from a larger grid (x) by the following commands:
I = abs(x)<0.5;
alpha = x(I);
My problem is that this criteria is not being able to filter x = -0.5. My question is, does Matlab think abs(-0.5)>0.5?
What am i doing wrong here? Please help.
1 commentaire
Stephen23
le 21 Jan 2016
You should read about the precision limits of floating point values:
And some external links on this topic:
Réponse acceptée
Walter Roberson
le 21 Jan 2016
Your value is probably not being calculated as exactly -0.5 . -0.5 is exactly representable in binary floating point, but different ways of calculating what "should" be -0.5 do not always give that exact value. If you add 0.5 to the value you think should be -0.5 you will probably find that the result is not exactly 0.
3 commentaires
Walter Roberson
le 21 Jan 2016
-0.5 - tol < x & x < 0.5 + tol
There are some inrange() contributions in the File Exchange. You need to watch out for the boundary conditions for them.
Steven Lord
le 21 Jan 2016
x = cos(2*pi/3);
y = -0.5;
format hex
[x; y]
The value stored in x is not exactly -0.5. It's close, but you can see that the bit patterns of the numbers aren't the same.
format
difference = x-y
Why is this, you may ask? The PI function doesn't return the irrational value representing the exact ratio between the circumference of a circle and its diameter, for one thing. Instead, PI returns the double precision value closest to the irrational value. That's not enough to compute the circumference of the universe to the nearest atom (that would require about 39 digits according to the Wikipedia page for pi) but it's good enough for most computations.
Plus de réponses (2)
Image Analyst
le 20 Jan 2016
If you want =, then use =
indexesInRange = abs(x) <= 0.5;
alpha = x(indexesInRange);
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!