删除彼此相邻出现的重复项,但如果以后再次出现则保留它 [英] Remove duplicates appearing next to each other, but keep it if it appears again later

查看:131
本文介绍了删除彼此相邻出现的重复项,但如果以后再次出现则保留它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个矢量可能看起来像这样:

I have a vector that could look like this:

v = [1 1 2 2 2 3 3 3 3 2 2 1 1 1];

也就是说,相等元素的数量可以变化,但是它们总是以1的步长递增和递减.

that is, the number of equal elements can vary, but they always increase and decrease stepwise by 1.

我想要的是一种简单的方法,可以像这样留下一个新向量:

What I want is an easy way to be left with a new vector looking like this:

v2 = [ 1 2 3 2 1];

保留所有不同元素(按在v中出现的正确顺序),但每个元素中只有一个.最好不要循环,因为我的向量通常长约10000个元素,并且已经在一个循环中,这是永远需要运行的.

holding all the different elements (in the right order as they appear in v), but only one of each. Preferably without looping, since generally my vectors are about 10 000 elements long, and already inside a loop that's taking for ever to run.

非常感谢您提供任何答案!

Thank you so much for any answers!

推荐答案

您可以使用 diff .您真正要问的是:删除任何与前面相同的元素.

You can use diff for this. All you're really asking for is: Delete any element that's equal to the one in front of it.

diff返回向量中所有相邻元素之间的差.如果没有差异,它将返回0. v(ind~=0)将为您提供所有值都不为零的元素.开头的1是为了确保第一个元素被计数.由于diff返回元素之间的差numel(diff(v)) = numel(v)-1.

diff return the difference between all adjacent elements in a vector. If there is no difference, it will return 0. v(ind~=0) will give you all elements that have a value different than zero. The 1 in the beginning is to make sure the first element is counted. As diff returns the difference between elements, numel(diff(v)) = numel(v)-1.

v = [1 1 2 2 2 3 3 3 3 2 2 1 1 1];
ind = [1 diff(v)];
v(ind~=0)
ans =
     1     2     3     2     1

如果您愿意,当然可以在一行中完成

This can of course be done in a single line if you want:

v([1, diff(v)]~=0)

这篇关于删除彼此相邻出现的重复项,但如果以后再次出现则保留它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆