Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

faster way to achieve unique() in matlab if assumed 1d pre-sorted vector?

I had good luck finding a way to achieve intersect() faster on stack overflow with a pre-sorted 1d vector, so I am hoping for the same luck for unique() ;)

Almost 1/4'th of my runtime is spent using unique(). I would like to speed this up, and I can assume it to be 1d pre-sorted vector. Is there any other low-level functions I can use directly to speed this up?

like image 619
gnychis Avatar asked Nov 17 '11 21:11

gnychis


People also ask

How do you find unique elements in a vector in MATLAB?

View MATLAB Command. Find the unique elements in a vector and then use accumarray to count the number of times each unique element appears. Create a vector of random integers from 1 through 5. a = randi ( [1 5],200,1); Find the unique elements in the vector. Return the index vectors ia and ic. [C,ia,ic] = unique (a);

How to get the unique value of a vector?

Furthermore the simpliest way to get unique value is to sort the vector. So the stable option should be a little bit longer to execute. Sign in to comment. Sign in to answer this question.

Should unique be sortable by default?

In my opinion unique should be "stable" by default. If someone wants to sort, than there is sort commant that for. What does sorting by default in unique has to do with removing duplicate values?


1 Answers

You can simply use diff to check whether consecutive elements are the same.

vector = [1 2 3 4 4 5];

uniqueVector = vector([true;diff(vector(:))>0])

uniqueVector =
     1     2     3     4     5
like image 199
Jonas Avatar answered Oct 02 '22 14:10

Jonas