Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove duplicates in an array but keep the same order?

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'
like image 939
Ben Fossen Avatar asked Jun 17 '10 20:06

Ben Fossen


People also ask

How do you remove duplicates from a list whilst preserving order?

If you want to preserve the order while you remove duplicate elements from List in Python, you can use the OrderedDict class from the collections module. More specifically, we can use OrderedDict. fromkeys(list) to obtain a dictionary having duplicate elements removed, while still maintaining order.


2 Answers

Here's one solution that uses some additional input and output arguments that UNIQUE has:

>> y = { 'd' 'f' 'a' 'g' 'g' 'a' 'w' 'h'};  %# Sample data
>> [~,index] = unique(y,'first');        %# Capture the index, ignore the actual values
>> y(sort(index))                           %# Index y with the sorted index

ans = 

    'd'    'f'    'a'    'g'    'w'    'h'
like image 71
gnovice Avatar answered Oct 15 '22 06:10

gnovice


In MATLAB R2012a, a new order flag was added:

>> y = {'d' 'f' 'a' 'g' 'g' 'a' 'w' 'h'};
>> unique(y, 'stable')
ans = 
    'd'    'f'    'a'    'g'    'w'    'h'
like image 39
Amro Avatar answered Oct 15 '22 06:10

Amro