How to sort matrix rows based on the frequency of elements in a single column?

I tried using the sortrows function in Matlab. Is there a way to use this function or any idea to sort the rows of a matrix based on the frequency of the column elements of this matrix.

As an example: I have this matrix

matrix = [1 3 1; 1 4 2; 2 5 4; 3 2 3; 5 5 4; 5 3 3; 4 3 2; 4 2 3; 3 6 4; 2 4 3]; 

I would like to get something similar to this:

 sorted_based_on_3rd_col = [2 4 3; 3 2 3; 4 2 3; 5 3 3; 2 5 4; 3 6 4; 5 5 4; 1 4 2; 4 3 2; 1 3 1] 

which is sorted based on the most common item in the third column. Thanks for any help!

+4
source share
2 answers

If you do not need an order of elements with equal frequency, you can do this like this:

 >> freq = accumarray(matrix(:,3), 1); >> [~, ind] = sort(freq(matrix(:, 3)), 1, 'descend'); % index that sorts matrix >> matrix(ind, :) % reshuffle matrix to sort ans = 3 2 3 5 3 3 4 2 3 2 4 3 2 5 4 5 5 4 3 6 4 1 4 2 4 3 2 1 3 1 

If you don't care, you need to pre-sort the matrix first. Since matlab sort is stable , this will keep the order of the elements equal in the second sort.

 >> matrix = sortrows(matrix, 1) matrix = 1 3 1 1 4 2 2 5 4 2 4 3 3 2 3 3 6 4 4 3 2 4 2 3 5 5 4 5 3 3 >> freq = accumarray(matrix(:,3),1); >> [~, ind] = sort(freq(matrix(:,3)), 1, 'descend'); >> matrix(ind, :) ans = 2 4 3 3 2 3 4 2 3 5 3 3 2 5 4 3 6 4 5 5 4 1 4 2 4 3 2 1 3 1 
+3
source

This is one way:

 x = matrix(:,3); [c,b] = histc(x,unique(x)) [~,idx] = sort(c(b),'descend') out = matrix(idx,:) 
+4
source

All Articles