MATLAB: Counting runs in a vector

countingrunssequences

Hi all, I have the following vector for which I would like to count "runs", i.e. successive increments in each direction.
v = [0 0 1 2 3 2 2 1 2 2 1 2 3 4 3];
The desired output would look like
out = [3 2 1 1 3 1]
.. because from the first to the fifth element, v moves 3, and from the fifth to the eighth, switches direction and retracts 2, and so on.

Best Answer

>> V = [0,0,1,2,3,2,2,1,2,2,1,2,3,4,3];
>> W = V([true,0~=diff(V)]); % remove repeats
>> diff(W([true,0~=diff(sign(diff(W))),true]))
ans =
3 -2 1 -1 3 -1
Take the absolute value if you need to.