2010-03-24 50 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

相關問題