如何删除数组中的重复项但保持相同的顺序? [英] How can I remove duplicates in an array but keep the same order?
本文介绍了如何删除数组中的重复项但保持相同的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
y = {'d''f''a''g' 'g''a''w''h'}
我使用唯一(y)
以摆脱重复,但按字母顺序排列字符串:
>>唯一(y)
ans =
'a''d''f''g''h''w'
我想删除重复项,但保持相同的顺序。我知道我可以写一个函数做这个,但是想知道是否有一个更简单的方法使用独特的
删除重复,同时保持相同的顺序只是重复的删除。 p>
我希望它返回:
>>唯一(y)
ans =
'd''f''a''g''w'''''
解决方案
这里有一个解决方案,使用一些额外的输入和输出参数 UNIQUE 有:
>> y = {'d''f''a''g''g''a''w''h'}; %#样本数据
>> [〜,index] = unique(y,'first'); %#捕获索引,忽略实际值
>> y(sort(index))%#索引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屋!
查看全文