MATLAB Answers

How to quickly find the maximum group of same rows in a matrix?

1 view (last 30 days)
Benson Gou
Benson Gou on 18 Nov 2019
Commented: Star Strider on 2 Dec 2019
Dear All,
I have a matrix and there exist identical rows in the matrix. I want to find the maximum group of identical rows in this matrix. For example, I have a matrix as follows:
A = [0 1 0 1 0 0 0 0; 1 0 0 0 1 0 0 0; 1 0 0 0 1 0 0 0; 1 1 0 0 0 0 0 0; 0 0 1 0 0 0 0 1; 0 0 0 0 0 1 1 0; 0 1 0 1 0 0 0 0; 0 1 0 1 0 0 0 0].
There are two groups of identical rows: {row 1, row 7 and row 8}, {row 2, row 3}. So the answer is {row 1, row 7, row 8}. But how can I quickly find it?
Best regsards,
Benson

  0 Comments

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 18 Nov 2019
Try this:
A = [0 1 0 1 0 0 0 0; 1 0 0 0 1 0 0 0; 1 0 0 0 1 0 0 0; 1 1 0 0 0 0 0 0; 0 0 1 0 0 0 0 1; 0 0 0 0 0 1 1 0; 0 1 0 1 0 0 0 0; 0 1 0 1 0 0 0 0];
[Au,~,idx] = unique(A, 'rows');
tally = accumarray(idx, 1);
Out = A(idx == max(tally),:) % The Rows Themselves
RowIdx = find(idx == max(tally)) % The Row Indices
producing:
RowIdx =
1
7
8

  6 Comments

Show 3 older comments
Star Strider
Star Strider on 23 Nov 2019
It is strange that my earlier code did not work on the new matrix.
With a slight edit, this version works correctly on both the original ‘A’ and the new ‘A’:
[Au,~,idx] = unique(A, 'rows');
tally = accumarray(idx, 1);
[~,maxidx] = max(tally);
Out = A(idx == maxidx,:) % The Rows Themselves
RowIdx = find(idx == maxidx) % The Row Indices
producing for the new ‘A’:
Out =
1 0 0 0 0 0 1 0 0
1 0 0 0 0 0 1 0 0
RowIdx =
3
4
and the correct result (posted previously) for the original ‘A’.
Benson Gou
Benson Gou on 2 Dec 2019
Dear Star,
Thanks a lot for your great help. Now it works very well.
Happy Holidays!
Bension

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!