删除彼此相邻出现的重复项,但如果以后再次出现则保留它

编程入门 行业动态 更新时间:2024-10-10 01:24:32
本文介绍了删除彼此相邻出现的重复项,但如果以后再次出现则保留它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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)

更多推荐

删除彼此相邻出现的重复项,但如果以后再次出现则保留它

本文发布于:2023-10-27 23:54:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534899.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!