查看单个帖子
旧 2019-12-10, 20:41   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
帖子 如何删除数组中的重复项但保持相同顺序?

我在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'

回答:

这是一个使用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'

更多&回答...
poster 当前离线   回复时引用此帖