Why does MODE function return erroneous results in my script in MATLAB 8.0 (R2012b)?
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
MathWorks Support Team
am 25 Okt. 2013
Beantwortet: MathWorks Support Team
am 25 Okt. 2013
Consider the following:
pts = [-0.6 -6;-0.2 0;0 3;-0.8 -9;-2 1;-0.4 -3];
m=(pts(2:end,2)-ones(length(pts(:,1))-1,1)*pts(1,2)) ./ (pts(2:end,1)-ones(length(pts(:,1))-1,1)*pts(1,1))
The output is:
m =
15.0000
15.0000
15.0000
-5.0000
15.0000
However, when I type 'mode(m)' I get a clearly incorrect answer:
mode(m)
ans =
-5
And, when I do the following, I get the correct answer:
zz=str2num(num2str(m));
mode(zz)
ans =
15
Can you explain what is going on here?
Akzeptierte Antwort
MathWorks Support Team
am 25 Okt. 2013
The observed behavior is expected as the numbers '15' in the array 'm' are not all equal. This can be verified by changing the display format to 'long':
>> format long
>> m
m =
15.000000000000002
15.000000000000000
14.999999999999995
-5.000000000000000
15.000000000000004
When all the elements are different, MODE just returns the smallest, which in this case is '-5'.
The MODE function is most useful with discrete or coarsely rounded data. Hence, 'rounding' the data or reducing the precision will be useful here. There are many ways to reduce the precision:
>> mnew = double(single(m));
>> mode(mnew)
ans =
15
>> mnew = str2num(num2str(m)); % NUM2STR by default uses a precision of 16 digits
>> mode(mnew)
ans =
15
By the way, If we use a ’32-digit’ precision with NUM2STR, we get:
>> mnew2 = str2num(num2str(m,32))
>> mode(mnew2)
mnew2 =
15.000000000000002
15.000000000000000
14.999999999999995
-5.000000000000000
15.000000000000004
ans =
-5
In conclusion, it is recommended to use coarsely rounded inputs along with MODE function to avoid precision issues such as the above.
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Array Geometries and Analysis finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!