Find indexes of unique in a matlab vector?

Tag: matlab , vector Author: lohglohg Date: 2012-03-02

I have a vector M with possibilities of multiple duplicates, and I want to create an index vector that ignores all the duplicates. I tried [C,ia,ib] = unique(M) but I don't quite know how to use ia and ib.

Edit: Sorry I missed an important detail, I is an existing index vector, it needs to get rid of all index that contain duplicate value. So the original vector looks like M(I) and I want to 'clean up' up I, if I do directly ia = I it won't preserve the original data of I.

Best Answer

From http://www.mathworks.co.uk/help/techdoc/ref/unique.html:

[C,ia,ic] = unique(A) also returns index vectors ia and ic, such that C = A(ia) and A = C(ic).

For example:

[C ia ic] = unique([11 22 11 33 22 44])

results in:

C =

   11   22   33   44

ia =

   3   5   4   6

ic =

   1   2   1   3   2   4

Update

In your updated scenario, you should do I = I(ia).

comments:

Thanks that solved my problem!

Other Answer1

You can use optional outputs.

a=round(10*rand(1,10)) 

[dummy I]=unique(a,'first'); 

u=a(sort(I));