2010-06-17 127 views
24

我在MATLAB这个单元阵列:如何删除数组中的重复项,但保持相同的顺序?

y = { 'd' 'f' 'a' 'g' 'g' 'a' 'w' 'h'} 

我用unique(y)摆脱重复的,但它重新排列字母顺序排列的字符串:我想删除重复的,但保持

>> unique(y) 

ans = 

'a' 'd' 'f' 'g' 'h' 'w' 

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

我希望它返回此:

>> unique(y) 

ans = 

'd' 'f' 'a' 'g' 'w' 'h' 
+2

我想通过给答案Amro是现在实现这一目标的最佳方式。 '独特(y,'stable')' – 2013-07-23 08:39:43

回答

27

下面是一个使用一些额外的输入和输出参数是UNIQUE有一个解决办法:

>> 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' 
+2

现在为什么我不这样想? +1 – Doresoom 2010-06-17 20:46:11

+0

+1:我在我的路径中已经有了一个名为'uniq.m'的函数,可以完全做到这一点,我一直都在使用它:) – Amro 2010-06-17 22:08:46

6

如果你看一下unique的文档,还有与排序的数组一起返回一个索引的选项。您可以指定是否要将数字的第一次或最后一次出现返回到索引。

例如:

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

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

回报

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

您可以按照您的订单阵列和存储旁边的指数

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

最后重新索引A

b=b(index) 
+0

+1:看起来我们在同一时间修改了我们的答案。 – gnovice 2010-06-17 20:48:00

21

在MATLAB R2012a,新order flag加入:

>> y = {'d' 'f' 'a' 'g' 'g' 'a' 'w' 'h'}; 
>> unique(y, 'stable') 
ans = 
    'd' 'f' 'a' 'g' 'w' 'h' 
相关问题