Count unique rows in a matrix

Consider the following array:

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

      

How can I count the number of unique strings in this array? The answer is in example 2 , because the string is [1 2 3]

repeated twice.

+3


source to share


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


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







All Articles