list 如何删除数组中的重复项但保持相同的顺序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3065387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I remove duplicates in an array but keep the same order?
提问by Ben Fossen
I have this cell array in MATLAB:
我在 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)
用来摆脱重复,但它按字母顺序重新排列字符串:
>> 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.
我想删除重复项但保持相同的顺序。我知道我可以编写一个函数来做到这一点,但想知道是否有一种更简单的方法unique
来删除重复项,同时保持相同的顺序,只是删除重复项。
I want it to return this:
我希望它返回这个:
>> unique(y)
ans =
'd' 'f' 'a' 'g' 'w' 'h'
回答by gnovice
Here's one solution that uses some additional input and output arguments that UNIQUEhas:
这是一种使用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'
回答by Amro
In MATLAB R2012a, a new order flagwas added:
在 MATLAB R2012a 中,添加了一个新的订单标志:
>> y = {'d' 'f' 'a' 'g' 'g' 'a' 'w' 'h'};
>> unique(y, 'stable')
ans =
'd' 'f' 'a' 'g' 'w' 'h'
回答by Doresoom
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.
如果您查看 的文档unique
,则可以选择返回索引和排序数组。您还可以指定是否希望将第一次或最后一次出现的数字返回到索引中。
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]
b=[1, 2, 3, 4, 5]
和 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=b(index)