Filter löschen
Filter löschen

The code does not work with 1.7

2 Ansichten (letzte 30 Tage)
net
net am 30 Nov. 2011
This code works normally accept 1.7
it does not count 1.7
I coul not understand why
y=[1.3,1.3,1.7,1.3,1.7,1.6,1.8,1.9,1.6]; %y=[1.7,1.7,1.7,1.7,1.7,1.7,1.7,1.7,1.7]; x=1;
for i=1:0.1:1.9
v(x)=sum(y==i);
x=x+1;
end
v
  2 Kommentare
Wayne King
Wayne King am 30 Nov. 2011
what are you trying to do with this code???
net
net am 30 Nov. 2011
I wanted to count elements.
1.3 => 3 times
1.7 => 2 times etc.
These answers solved my problem.
Thanks for the all of answers.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Titus Edelhofer
Titus Edelhofer am 30 Nov. 2011
Hi,
this is due to roundoff: 0.1 is not representable as a finite number in binary system. Note the following:
i=1:0.1:1.9;
i(9)-1.8
ans =
-2.2204e-016
And then your test on equality fails ...
Titus
  1 Kommentar
Andrei Bobrov
Andrei Bobrov am 30 Nov. 2011
sum(y == i1) -> sum(abs(y-i1) < 100*eps)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (3)

Robert Cumming
Robert Cumming am 30 Nov. 2011
As said above you have encountered the problem of floating point arithmetic, if change your counter to be 1 instead of 0.1 (and change your inner the line to:
v = sum (y==i/10)
you will see 1.7 is counted.
Its worth understanding that computer are not exact due to the way they store information in memory, for example try:
[0.3-0.2 == 0.1]
[0.3-0.2-0.1]
They answers are not what you might expect... Note this is not a problem of Matlab alone. Have a read of this answer

Junaid
Junaid am 30 Nov. 2011
Anyway you can do what ever you want from this simple one lines.
v =hist(y,[1:.1:2])
This is simple. Take the histgram. The number of bins are decided by [1:.1:2].

net
net am 30 Nov. 2011
Thanks for the answers.

Kategorien

Mehr zu MATLAB finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by