计算矩阵中的唯一行

时间:2015-07-10 15:43:19

标签: matlab matrix

考虑以下数组:

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

如何计算此数组中唯一行的数量?示例中的答案是 2 ,因为[1 2 3]行重复了两次。

2 个答案:

答案 0 :(得分:4)

unique'rows'属性一起使用以获取唯一行,并通过获取输出行方向的size来计算它们。

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

替代方案,您可以使用numel计算unique的第二个输出:

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

答案 1 :(得分:1)

单行解决方案sumanydiff& 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.
相关问题