在MATLAB矩阵中找到重复次数最多的行

5
我正在寻找一种在MATLAB中查找矩阵中最常重复(即众数)行的函数。类似于以下内容:
>> A = [0, 1; 2, 3; 0, 1; 3, 4]

A =

 0     1
 2     3
 0     1
 3     4

然后运行:

>> mode(A, 'rows')

希望返回[0, 1],最好还有第二个输出,给出这一行发生的索引位置(即[1, 3])。

有人知道这样的函数吗?

2个回答

14

您可以使用UNIQUE获取唯一的行索引,然后在这些索引上调用MODE

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

1
谢谢。我认为最后一行应该是这样的:whereIdx = find(uIdx(modeIdx)==uIdx) - Bill Cheatham
@Bill Cheatham:是的,当然。这就是我在测试之后添加行的结果。 - Jonas
@sinoTrinity:谢谢。问题已经被修复。 - Jonas
没问题。最后一条语句可能还有问题。whereIdx 应该是 A 的索引,而不是现在的 uA,对吧? - sinoTrinity
1
@Jonas:我相信你的意思是:“whereIdx = find(uIdx==modeIdx)” - Amro

2
答案可能不正确。尝试使用A = [2, 3; 0, 1; 3, 4; 0, 1]。应该如下所示:
[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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接