I have this cell array in MATLAB:
y = { 'd' 'f' 'a' 'g' 'g' 'a' 'w' 'h'}
I use unique(y)
to get rid of the duplicates but it rearranges the strings in alphabetical order:
>> unique(y)
ans =
'a' 'd' 'f' 'g' 'h' 'w'
I want to remove the duplicates but keep the same order. I know I could write a function do do this but was wondering if there was a simpler way using unique
to remove duplicates while keeping the same order just with the duplicates removed.
I want it to return this:
>> unique(y)
ans =
'd' 'f' 'a' 'g' 'w' 'h'
If you look at the documentation for
unique
, there's the option to return an index along with the sorted array. You can specify whether you want the first or last occurrence of a number to be returned to the index as well.For example:
returns
b=[1, 2, 3, 4, 5]
andm=[5, 4, 2, 3, 1]
You can sort your order array and store the index next
and finally re-index b
In MATLAB R2012a, a new order flag was added:
Here's one solution that uses some additional input and output arguments that UNIQUE has: