MATLAB: How to count the number of consecutive identical elements (in both the directions) in a binary vector

clusteringconsecutive numbervector

Suppose I have a binary vector
X = [0 0 0 0 1 1 1 0 1 1 1 1]
I want to characterize each element with the number of identical elements occurring in consecutive positions in both the directions. For instance, the desired output should look like:
Y = [4 4 4 4 3 3 3 1 4 4 4 4].
I found a similar thread, but it counts only in the forward direction. Thanks in advance for any sort of assistance.

Best Answer

X = [0 0 0 0 1 1 1 0 1 1 1 1];
[B, N] = RunLength(X);
Y = RunLength(N, N);
If you do not have a C-compiler for the fast C-Mex function, use RunLength_M.
Or with Matlab code:
d = [true, diff(X) ~= 0, true]; % TRUE if values change
n = diff(find(d)); % Number of repetitions
Y = repelem(n, n)