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?
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
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
精彩评论