删除重复项 - ** 仅当重复项按顺序出现时
我想做类似于以下的事情,但我只想删除“g”和“g”,因为它们是相继出现的重复项。我也想保持顺序相同。
任何帮助将不胜感激!
我在 MATLAB 中有这个元胞数组:
y = { 'd' 'f' 'a' 'g' 'g' 'w' 'a' 'h'}
ans =
'd' 'f' 'a' 'w' 'a' 'h'
I would like to do something similar to the following, except I would only like to remove 'g' and'g' because they are the duplicates that occur one after each other. I would also like to keep the sequence the same.
Any help would be appreciated!!!
I have this cell array in MATLAB:
y = { 'd' 'f' 'a' 'g' 'g' 'w' 'a' 'h'}
ans =
'd' 'f' 'a' 'w' 'a' 'h'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当我的第一个答案(如下)用于多个重复项时,出现错误(感谢 grantnz)。这是更新版本:
旧答案
如果您的“单元向量”始终仅包含单个字符元素,您可以执行以下操作:
There was an error in my first answer (below) when used on multiple duplicates (thanks grantnz). Here's an updated version:
OLD ANSWER
If your "cell vector" always contains only single character elements you can do the following:
像这样看:当且仅当(1)它是第一个元素或(2)它的前一个元素与它不同并且或者(3)它是最后一个元素时,您想要保留一个元素(4) 其后继者与其不同。所以:
或者,也许更好,
Look at it like this: you want to keep an element if and only if either (1) it's the first element or (2) its predecessor is different from it and either (3) it's the last element or (4) its successor is different from it. So:
or, perhaps better,
这应该有效:
或者稍微更紧凑
更正:上面不会删除两个重复项
顺便说一句,即使有多个重复序列,这也有效,
例如,
This should work:
or slightly more compactly
Correction : The above wont remove both the duplicates
BTW, this works even if there are multiple duplicate sequences
eg,