(Slightly) Faster way to compute number of unique elements in matlab matrix

Alec Jacobson

August 31, 2016

weblog/

The standard way to compute the number of unique entries in a matlab matrix A is:

numel(unique(A))

If our entries are positive integers, we can try to do the same thing using sparse with:

nnz(sparse(A(:),1,1,size(A,1),1))

but actually this is slower.

I don't see a way to avoid a sort. I came up with this,

sum(diff(sort(F(:)))~=0)+1

As far as I can tell, this will work for matrices that don't have infs and nans. It's slightly faster than number(unique(A)). I have a feeling I'm only winning anything here because I'm avoiding overhead within unique