Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I tried using sortrows function in Matlab. Is there any way using this function or any idea to sort rows of a matrix based on frequency of elements of a column of that 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 most frequent element on third column. Thanks for any help!

like image 912
Jose Avatar asked Mar 16 '23 04:03

Jose


1 Answers

This is one way:

x = matrix(:,3);
[c,b] = histc(x,unique(x))
[~,idx] = sort(c(b),'descend')
out = matrix(idx,:)
like image 138
Robert Seifert Avatar answered Apr 27 '23 00:04

Robert Seifert