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

走远了吗. 提交于 2019-11-28 10:43:21
gnovice

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'

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'

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:

a=[5, 3, 4, 2, 1, 5, 4];

[b,order]=unique(a,'first')

returns

b=[1, 2, 3, 4, 5] and m=[5, 4, 2, 3, 1]

You can sort your order array and store the index next

[~,index]=sort(order) %# use a throw-away variable instead of ~ for older versions

and finally re-index b

b=b(index)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!