MATLAB: Replacing repeated elements with the index of the first element

indexMATLABunique

So I have a vector with repeated values, that looks something like [2 2 2 2 8 8 8 8 3 3 3 3] etc. I would like to change it to give: [2 1 1 1 8 5 5 5 3 9 9 9] i.e replacing the duplicate values with index of the first duplicate value
Thanks

Best Answer

a = [3137 3137 3137 3137 3137 3137 3137 3137 1521 1521 1521 1521 1521 1521 1521 1521 1521 1521 1521 1521 1521 1521 1521 1521 401 401 401 401 401];
[a1,b1,c1] = unique(a,'stable');
out = b1(c1);
out(b1) = a1;