考虑以下数组:
a = [1 2 3;
1 1 1;
1 2 3]
如何计算此数组中唯一行的数量?示例中的答案是 2 ,因为[1 2 3]
行重复了两次。
答案 0 :(得分:4)
将unique
与'rows'
属性一起使用以获取唯一行,并通过获取输出行方向的size
来计算它们。
uniquerows = size( unique(a,'rows'), 1)
替代方案,您可以使用numel
计算unique
的第二个输出:
[~,c] = unique(a,'rows')
uniquerows = numel(c)
答案 1 :(得分:1)
单行解决方案sum
,any
,diff
& 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.