문제

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!

도움이 되었습니까?

해결책

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top