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

前端 未结 3 1788
悲哀的现实
悲哀的现实 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'
    

提交回复
热议问题