在值更改之前查找连续元素的数量(MATLAB) [英] Find number of consecutive elements before value changes (MATLAB)
问题描述
我有一个大小(行)的向量,包含值1,2和3.它们没有特定"顺序,因此数组的样本为[1,1,1,1 ,2,2,2,1,1,2,2,3,3].我想做的是找到连续数量的相同元素,但是有一些限制.
I have a (row)vector of some size, containing the values 1,2 and 3. They are in there in no 'specific' order, so a sample of the array would be [1,1,1,1,2,2,2,1,1,2,2,3,3]. What I want to do is find the consecutive number of identical elements, but with some restrictions.
我想要的是制作一个新的数组,其中的元素表示:
What I want is to make new arrays of which the elements denote:
- 更改为2之前的连续1的数量
- 更改为1之前的连续2个数字
- 变为2之前的连续2个数字
- 变为2之前的连续3个数字
因此,对于我给出的示例,数组将为
So for the example I have given, the arrays would be
[4,2]
[3]
[2]
[]
我不确定该如何解决.我可以使用diff函数来查找它在哪里更改符号,但是要弄清楚到底发生了什么更改会有些困难,对吧?
I'm not sure how to tackle this. I can use the diff function to find where it changes sign, but then it'll be a little tough to figure out exactly what change has occured, right?
该方法不必超级快,因为我只需要对大约10 ^ 5个数据点执行几次.
The method does not have to be super fast, as I only have to do this a few times for around 10^5 datapoints.
推荐答案
此方法将按照您在问题中指定的方式对事物进行分组:
This approach will group things the way you specified in the question:
a=[1,1,1,1,2,2,2,1,1,2,2,3,3]
b = diff(a)
c = find(b)
d = diff([0,c]);
type1 = d(b(c) == 1 & a(c) == 1);
type2 = d(b(c) == -1 & a(c) == 2);
type3 = d(b(c) == 1 & a(c) == 2);
type4 = d(b(c) == -1 & a(c) == 3);
type1 =
4 2
type2 =
3
type3 =
2
type4 =
Empty matrix: 1-by-0
这篇关于在值更改之前查找连续元素的数量(MATLAB)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!