Sorting the elements of an array by the frequency of its elements

Is it possible in matlab / octave to use a function sort

to sort an array based on the relative frequency of their elements?

For example the array

m= [4,4,4,10,10,10,4,4,5]

      

should result in this array:

[5,10,10,10,4,4,4,4,4]

      

5

is the less frequent element and is located at the top, and 4

is the most frequent, and at the bottom - below. Should I use the indexes provided histcount

?

+3


source to share


3 answers


One way would be to use accumarray

to find the count of each number (I suspect you can use histcounts(m,max(m)))

, but then you need to clear all 0

s).

m = [4,4,4,10,10,10,4,4,5];

[~,~,subs]=unique(m);
freq = accumarray(subs,subs,[],@numel);
[~,i2] = sort(freq(subs),'descend');

m(i2)

      




By taking my approach with ms , you can get a simpler solution:

m = [4,4,4,10,10,10,4,4,5];

[U,~,i1]=unique(m);
freq= histc(m,U);
[~,i2] = sort(freq(i1),'descend');

m(i2)

      

+3


source


The following code first calculates how often each item occurs and then uses runLengthDecode

unique items to expand.

m = [4,4,4,10,10,10,4,4,5];

u_m = unique(m);

elem_count = histc(m,u_m);
[elem_count, idx] = sort(elem_count);

m_sorted = runLengthDecode(elem_count, u_m(idx));

      


Definition runLengthDecode

copied from this answer :

For MATLAB R2015a +:



function V = runLengthDecode(runLengths, values)
if nargin<2
    values = 1:numel(runLengths);
end
V = repelem(values, runLengths);
end

      


For versions up to R2015a:

function V = runLengthDecode(runLengths, values)
%// Actual computation using column vectors
V = cumsum(accumarray(cumsum([1; runLengths(:)]), 1));
V = V(1:end-1);
%// In case of second argument
if nargin>1
    V = reshape(values(V),[],1);
end
%// If original was a row vector, transpose
if size(runLengths,2)>1
    V = V.'; %'
end
end

      

+3


source


You can count the number of reps bsxfun

, sort

and apply this to the sort m

:

[~, ind] = sort(sum(bsxfun(@eq,m,m.')));
result = m(ind);

      

+2


source







All Articles