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

前端 未结 3 1781
悲哀的现实
悲哀的现实 2020-12-10 10:33

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 dup

相关标签:
3条回答
  • 2020-12-10 10:58

    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'
    
    0 讨论(0)
  • 2020-12-10 10:58

    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'
    
    0 讨论(0)
  • 2020-12-10 11:23

    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)
    
    0 讨论(0)
提交回复
热议问题