Pregunta

By the period I mean this :

Say I have a vector

v = [1,1,1 , 2,2,2 , 3,3,3];
period(v)

ans = 3

This vector should return 3 since the value changes in every 3rd item.

I can simply return the first index where the value changes, but I'm wondering if there is a built-in function, preferrably also working with non-uniform input. i.e. the last sequence could be smaller than 3.

The closest thing I could find is seqperiod but it returns 9 (the length) for this vector.

Thanks for any help!

¿Fue útil?

Solución

If you know that the period remains constant for the entire array, you could use the diff() function and pull out the location of the first value like this:

>> diff_out = find(diff(v));
>> diff_out(1)

    ans =
    3

Alternatively, if the period varies, you could run an additional diff to get a vector that represents number of elements between changes like so:

>> diff([0,find(diff(v))])
   ans =

   3     3
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top