Violation of logical indexing criteria problem

조회 수: 3 (최근 30일)
Sudipta Ray
Sudipta Ray 2016년 1월 20일
댓글: Steven Lord 2016년 1월 21일
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.

채택된 답변

Walter Roberson
Walter Roberson 2016년 1월 21일
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
Walter Roberson
Walter Roberson 2016년 1월 21일
-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
Steven Lord 2016년 1월 21일
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.

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

추가 답변 (2개)

Image Analyst
Image Analyst 2016년 1월 20일
If you want =, then use =
indexesInRange = abs(x) <= 0.5;
alpha = x(indexesInRange);
  댓글 수: 1
Sudipta Ray
Sudipta Ray 2016년 1월 21일
Sorry about the ambiguity. I want to filter "out" x = -0.5, not include it. That is why I used "strictly less than (<)" condition. Matlab is somehow finding
abs(-0.5)< 0.5
and the value x = -0.5 is getting into my selection, which I don't want.

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


Sudipta Ray
Sudipta Ray 2016년 1월 21일
I have tried some fix, now it is working ok
tol = 1e-15;
I = abs(x)<r-tol;
still, if anyone has a better solution, please post it. I have considered "r-tol" because that solves my problem and not "r+tol". But this is too specific and works because the value
abs(cos(2*pi/3)) > 0.5.
That is why for my case only x = -0.5 was creating a problem, and not x = 0.5.

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by