Consider the following array:
a = [1 2 3;
1 1 1;
1 2 3]
How can I count the number of unique rows in this array? The answer in the example is 2, because the [1 2 3] row is repeated twice.
Use unique with the 'rows' property to get the unique rows and count them by obtaining the size in row direction of the output.
uniquerows = size( unique(a,'rows'), 1)
Alternative you could count the second output of unique with numel:
[~,c] = unique(a,'rows')
uniquerows = numel(c)
One-liner solution with sum, any, diff & sortrows -
count_unqrows = sum(any(diff(sortrows(a),1),2))+1
Benchmarks -
Benchmarking Code to compare all 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With