Sadegh
Sadegh

Reputation: 411

Group identical rows of a matrix, together with their frequency count

The easiest way to explain the question is by an example:

>> A = [1 5; 1 5; 1 6; 1 6; 1 6; 1 6; 1 7; 2 5; 2 6; 2 6; 2 6; 2 7; 2 7; 2 8]

A =

 1     5
 1     5
 1     6
 1     6
 1     6
 1     6
 1     7
 2     5
 2     6
 2     6
 2     6
 2     7
 2     7
 2     8

What I want to have as output is something similar to

result =

     1     6     4
     1     5     2
     2     6     3
     2     7     2

Which means top two frequent pairs for each value in first column. So most frequent pairs came with 1 are 6 and 5 and most frequent pairs came with 2 are 6 and 7. 3rd column shows frequency of pairs.

I use matlab 2016 in linux.

Upvotes: 0

Views: 69

Answers (1)

Rishit Sanmukhani
Rishit Sanmukhani

Reputation: 2269

You could use unique and histc to count the frequency of occurrence of each row. Then using frequency, you can proceed with your calculations.

[unique_rows,~,ind] = unique(A,'rows');
counts = histc(ind,unique(ind));

Now, you could combine the frequency count and sort them.

arr = [unique_rows,counts];
[sorted,~]=sortrows(arr,[1 -3])

sorted =

 1     6     4
 1     5     2
 1     7     1
 2     6     3
 2     7     2
 2     5     1
 2     8     1

Upvotes: 3

Related Questions