MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   如何删除数组中的重复项但保持相同顺序? (https://www.labfans.com/bbs/showthread.php?t=23541)

poster 2019-12-10 20:41

如何删除数组中的重复项但保持相同顺序?
 
我在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'

[B]回答:[/B]

这是一个使用[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/unique.html"]UNIQUE[/URL]具有一些其他输入和输出参数的解决方案:

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

[url=https://stackoverflow.com/questions/3065387]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 13:23

Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.