2015-07-10 69 views
3

考慮以下數組:矩陣計數獨特的行

a = [1 2 3; 
    1 1 1; 
    1 2 3] 

我怎麼能指望這個數組中唯一的行數?示例中的答案是,因爲[1 2 3]行重複了兩次。

回答

4

使用unique'rows'屬性獲取唯一行並通過在輸出的行方向獲取size來對它們進行計數。

uniquerows = size(unique(a,'rows'), 1) 

替代,你可以用numelunique第二輸出:

[~,c] = unique(a,'rows') 
uniquerows = numel(c) 
1

sum一行代碼的解決方案,anydiff & sortrows -

count_unqrows = sum(any(diff(sortrows(a),1),2))+1 

基準 -

基準測試代碼比較所有解決辦法,到目前爲止發佈:

%// Input 
a = randi(1000,5000,5000); 

%// Warm up tic/toc. 
for k = 1:50000 
    tic(); elapsed = toc(); 
end 

disp('-------------- With SUM, ANY, DIFF, SORTROWS') 
tic 
out1 = sum(any(diff(sortrows(a),1),2))+1; 
toc, clear out1 

disp('-------------- With UNIQUE, NUMEL') 
tic 
[~,c] = unique(a,'rows'); 
out2 = numel(c); 
toc, clear out2 

disp('-------------- With UNIQUE, SIZE') 
tic 
out3 = size(unique(a,'rows'), 1); 
toc, clear out3 

結果:

-------------- With SUM, ANY, DIFF, SORTROWS 
Elapsed time is 0.502803 seconds. 
-------------- With UNIQUE, NUMEL 
Elapsed time is 1.237495 seconds. 
-------------- With UNIQUE, SIZE 
Elapsed time is 1.155051 seconds. 
+0

比較我與你的第一個解決方案,將是更公平的 - 但你更快在任何情況下;)+1 – thewaywewalk

+0

@thewaywewalk好吧,它似乎有一點改善。還補充說! :) – Divakar