2012-12-14 29 views
2

所有相同值的行我有一個矩陣是這樣的:刪除在MATLAB

1 2 4 
4 5 6 
1 2 4 
7 9 6 
1 2 4 

,我想刪除同一行。 我的新矩陣應該是

4 5 6 
7 9 6 

我該怎麼做?

回答

1

我覺得這個劇本可以做你想做的:

B= A; 
position = 1; 
condition = true; 
bSize = size(B,1); 
while (position < bSize) 
    [~,~,ic] = unique(B,'rows'); 
    changes = find(ic(position:end,:)== ic(position)); 
    if (length(changes)>1) 
     B(changes+position-1,:)= []; 
     bSize = size(B,1); 
    else 
     position = position+1; 
    end 
end 
disp(B) 
+0

太棒了!而在兩個矩陣的情況下?例如:a = [1,2,4; 4,5,6; 1 2 4; 7,9,6; 1 2 4]和b = [3 2 1; 3 4 5; 3 2 1; 4 6 7; 2 8 9]我想刪除具有相同值和相同索引的行,以獲得a1 = [4 5 6; 7 9 6; 1 2 4]和b1 = [3 4 5; 4 6 7; 2 8 9] – brio

1

您可以嘗試從所有其他行減去一行,如果任何行包含全零,則知道它包含重複元素。

4

的好去處,開始是:

b = unique(A, 'rows') 
+0

巧妙的把戲,我不知道那個命令! – PearsonArtPhoto

+2

但這並沒有解決原來的問題。您的解決方案不會返回[4,5,6; 7,9,6]。你的靈魂會返回[1,2,4; 4,5,6; 7,9,6] – KatyB

5

一個更完整的解決方案,基於@tayler的unique(,'rows')

[uA, ~, ui] = unique(A, 'rows'); % we have a single copy of each row. 
% it is now left to determine which row is duplicate 
n = hist(ui, 1:max(ui)); 
sel = n == 1; % pick only indices that appear once 
uA = uA(sel, :); 
+0

我喜歡你的解決方案,但它會排序A矩陣,這可能不是OP想要的 – Rasman

+1

@Rasman排序可以避免。請參閱http://stackoverflow.com/questions/13911689/how-to-delete-repeated-rows-with-out-re-ordering-them-in-matlab在'unique'中使用'stable'選項。 – Shai