我怎样才能删除重复的数组,但保持相同的顺序? [英] How can I remove duplicates in an array but keep the same order?

查看:140
本文介绍了我怎样才能删除重复的数组,但保持相同的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MATLAB这个单元阵列:

  Y = {'D''F''A''G''G''A''W''H'}

我用唯一的(Y)来摆脱重复的,但它在重新排列字母顺序串:

 >>唯一的(Y)ANS =ADFGHW

我想删除重复的,但保持相同的顺序。我知道我可以写一个函数不这样做,但不知道是否有使用简单的方法唯一同时保持只是删除了重复相同的顺序删除重复。

我想这回这样的:

 >>唯一的(Y)ANS ='D''F''A''G''W'H'


解决方案

下面是一个使用了的 UNIQUE 有:

 >> Y = {'D''F''A''G''G''A''W''H'}; %#示例数据
>> [〜,指数] =唯一的(Y,'第一'); %#捕获指数,忽略实际值
>> Y(排序(指数))%#标y与排序索引ANS =    'D''F''A''G''W'H'

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'

解决方案

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'

这篇关于我怎样才能删除重复的数组,但保持相同的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆