2010-03-24 56 views

回答

17

使用唯一的()来找到不同的行值。如果最终行数更少,则会有重复。它也会给你每个不同值的一个位置的索引。所有其他行索引都是您的重复项。

x = [ 
    1 1 
    2 2 
    3 3 
    4 4 
    2 2 
    3 3 
    3 3 
    ]; 
[u,I,J] = unique(x, 'rows', 'first') 
hasDuplicates = size(u,1) < size(x,1) 
ixDupRows = setdiff(1:size(x,1), I) 
dupRowValues = x(ixDupRows,:) 
+0

+1:当,击败我49秒! – gnovice 2010-03-24 18:02:49

+0

有谁知道Matlab用来计算这个算法吗? – Will 2012-04-07 01:45:18

0

运行,以及对于每一对,如果测试

row1 == row2

+1

这是有效的,但肯定比其他基本选项(即使用'unique()')更慢更冗长。 – bnaul 2010-03-24 18:02:05

4

可以使用的功能UNIQUESETDIFF来实现:

>> mat = [1 2 3; 4 5 6; 7 8 9; 7 8 9; 1 2 3]; %# Sample matrix 
>> [newmat,index] = unique(mat,'rows','first'); %# Finds indices of unique rows 
>> repeatedIndex = setdiff(1:size(mat,1),index) %# Finds indices of repeats 

repeatedIndex = 

    4  5 
+0

不应该'repeatedIndex'是'[3,4]'? – AVB 2010-03-24 18:04:07

+0

@AB:不,第四行和第五行是mat的重复。 – gnovice 2010-03-24 18:06:37

0

说你的矩阵是M:

[S,idx1] = sortrows(M); 
idx2 = find(all(diff(S,1) == 0,2)); 
out = unique(idx1([idx2;idx2+1])); 

出含有如有重复行的索引。

+0

只有当您的重复行彼此相邻时,这才会有效。 – gnovice 2010-03-24 18:17:26

+0

我的错误。错误的假设...... – upperBound 2010-03-24 18:27:03

+0

好吧,从技术上来说,OP永远不会明确表示重复的行是否彼此邻接。尽管不像使用UNIQUE那么普遍,但是这种解决方案在相邻重复的特定情况下运行*显着*更快,所以+1。 – gnovice 2010-03-24 18:37:22

相关问题