Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 784
Bill Cheatham Avatar asked Jan 24 '11 15:01

Bill Cheatham


2 Answers

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
like image 160
Jonas Avatar answered Sep 21 '22 14:09

Jonas


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
like image 38
sinoTrinity Avatar answered Sep 23 '22 14:09

sinoTrinity