Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count unique rows in matrix

Tags:

matrix

matlab

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.

like image 974
mimo Avatar asked Apr 20 '26 03:04

mimo


2 Answers

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)
like image 62
Robert Seifert Avatar answered Apr 23 '26 01:04

Robert Seifert


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.
like image 20
Divakar Avatar answered Apr 23 '26 03:04

Divakar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!