Bill Cheatham
Bill Cheatham

Reputation: 11917

Find the most repeated row in a MATLAB matrix

I am looking for a function to find the most repeated (i.e. modal) rows of a matrix in MATLAB. Something like:

>> A = [0, 1; 2, 3; 0, 1; 3, 4]

A =

 0     1
 2     3
 0     1
 3     4

Then running:

>> mode(A, 'rows')

would return [0, 1], ideally with a second output giving the indexes where this row occurred (i.e. [1, 3]'.)

Does anyone know of such a function?

Upvotes: 5

Views: 3184

Answers (2)

Jonas
Jonas

Reputation: 74940

You can use UNIQUE to get unique row indices, and then call MODE on them.

[uA,~,uIdx] = unique(A,'rows');
modeIdx = mode(uIdx);
modeRow = uA(modeIdx,:) %# the first output argument
whereIdx = find(uIdx==modeIdx) %# the second output argument

Upvotes: 14

sinoTrinity
sinoTrinity

Reputation: 1195

The answer may not be right. Try A = [2, 3; 0, 1; 3, 4; 0, 1]. It should be the following:

[a, b, uIdx] = unique(A,'rows');
modeIdx = mode(uIdx);
modeRow = a(modeIdx,:) %# the first output argument
whereIdx = find(ismember(A, modeRow, 'rows'))  %# the second output argument

Upvotes: 2

Related Questions