MATLAB: Count the adjacent same elements in a vector

countnumerical datavector

Hello! Assume we have a vector of A=[1 1 1 2 2 3 3 3 3 3 1 1]. A has three 1, two 2, five 3 and two 1.
I need to create a vector, such as B=[3 2 5 2] and their corresponding value C=[1 2 3 1].
Maybe i should use a struct, not sure. Glad for some help :/
thx.

Best Answer

L=cumsum([1, diff(A)~=0]);
B=splitapply(@sum,ones(size(A)),L)
C=splitapply(@min,A,L)