필터 지우기
필터 지우기

if statement not working

조회 수: 2 (최근 30일)
Vishan Gupta
Vishan Gupta 2018년 9월 25일
편집: Stephen23 2018년 9월 26일
I have a bunch of values in vector a=[0 0.3 0.55] I want to compare each of the value in a to the value of b=[0.3], if the compared value from a is greater than b, put that value in a vector a_front, if less, put in a_behind, if it is the same value, still put it in a_behind.
The problem is that when I do this, I get only 0 in a_behind, not 0 AND 0.3 like I want, it instead puts 0.3 into a_front with 0.55. Please help.
for k=1:size(a,2)
if a(k)>b
a_front(k)=a(k)
elseif a(k)<b
a_behind(k)=a(k)
else
a_behind(k)=a(k)
end
end
  댓글 수: 1
KSSV
KSSV 2018년 9월 25일
The above loop works fine...re check your result.

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

답변 (1개)

KSSV
KSSV 2018년 9월 25일
편집: KSSV 2018년 9월 25일
No if statement required.....read about logical indexing.
a=[0 0.3 0.55] ;
b = 0.3 ;
idx1 = a>b ;
idx2 = a<=b ;
a_front = a(idx1)
a_behind = a(idx2)
  댓글 수: 5
Walter Roberson
Walter Roberson 2018년 9월 26일
a(2)-0.3
ans =
5.55111512312578e-17
Your calculated 0.3 is the next representable number after your text 0.3 . This is not at all uncommon with floating point.
Stephen23
Stephen23 2018년 9월 26일
편집: Stephen23 2018년 9월 26일
"Ok so I've come across a weird problem..."
Not weird at all, you need to learn about floating point numbers, and why it is a bad idea to compare them for equality.
Note that 0.3 cannot be exactly represented using binary floating point numbers, in exactly the same way that you cannot write 1/3 with a finite number of decimal digits. What you see printed in the command window is the closest representation to 5 or 16 significant digits, depending on your current format setting. To see the "real" value download James Tursa's FEX submission:
Use James Tursa's num2strexact and you will see that none of those values really have the exact value 0.3. All you are looking at is a representation of those floating point numbers displayed in the command window, to the precision defined by your format setting. Just because you see 0.3 is displayed tells you nothing about the "real" floating point number's value.
Note that you can change how the value is displayed by changing the format.
You need to learn about the limits of floating point numbers. Start by reading these:
This is worth reading as well:

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

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by