MATLAB: How to count the number of consecutive numbers of the same value in an array

arrayconsecutive numbersconstant

I have an array given as
x = [1 1 1 2 2 1 1 1]
I'd like to know a way I could go through each individual element in the array, and getting a value for how many steps the number stays at the same value. For instance, for this example, the output I would be looking for would be
y = [2 1 0 1 0 2 1 0]
Where the first value of 1 stays constant for another 2 steps, the second stays constant for one more step etc.

Best Answer

% data
x = [1 1 1 2 2 1 1 1 3 3 3 3 3 5]
% engine
i = find(diff(x))
n = [i numel(x)] - [0 i]
c = arrayfun(@(X) X-1:-1:0, n , 'un',0)
y = cat(2,c{:})