29 lines
869 B
Text
29 lines
869 B
Text
function m = mode2(v)
|
|
sv = sort(v);
|
|
% build two vectors, vals and c, so that
|
|
% c(i) holds how many times vals(i) appears
|
|
i = 1; c = []; vals = [];
|
|
while (i <= numel(v) )
|
|
tc = sum(sv==sv(i)); % it would be faster to count
|
|
% them "by hand", since sv is sorted...
|
|
c = [c, tc];
|
|
vals = [vals, sv(i)];
|
|
i += tc;
|
|
endwhile
|
|
% stack vals and c building a 2-rows matrix x
|
|
x = cat(1,vals,c);
|
|
% sort the second row (frequencies) into t (most frequent
|
|
% first) and take the "original indices" i ...
|
|
[t, i] = sort(x(2,:), "descend");
|
|
% ... so that we can use them to sort columns according
|
|
% to frequencies
|
|
nv = x(1,i);
|
|
% at last, collect into m (the result) all the values
|
|
% having the same bigger frequency
|
|
r = t(1); i = 1;
|
|
m = [];
|
|
while ( t(i) == r )
|
|
m = [m, nv(i)];
|
|
i++;
|
|
endwhile
|
|
endfunction
|