Count unique rows in a matrix
2 answers
Use using property to get unique strings and count them, getting in the direction of the string in the output. unique
'rows'
size
uniquerows = size( unique(a,'rows'), 1)
Alternatively, you can read the second output unique
with : numel
[~,c] = unique(a,'rows')
uniquerows = numel(c)
+4
source to share
One-line solution sum
, any
, diff
and sortrows
-
count_unqrows = sum(any(diff(sortrows(a),1),2))+1
Benchmarks -
Comparative code to compare all the solution approaches posted so far:
%// 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
Results:
-------------- 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.
+1
source to share