MATLAB: How to count the number of consecutive identical element of each row in a binary matrix

arrayconsecutive numbercountmatrix

Matrix A contains only binary numbers: A=[0,0,0,0,1,1,0,0;1,0,1,1,1,1,0,0;0,1,1,0,1,0,0,1]
A = 0 0 0 0 1 1 0 0
1 0 1 1 1 1 0 0
0 1 1 0 1 0 0 1
I want to count the number of consecutive elements of each row (use first row as an example) in this way:
[1st consecutive 0, 2nd consecutive 0, 3rd consecutive 0, 4th consecutive 0, 1st consecutive 1, 2nd consecutive 1, 1st consecutive 0, 2nd consecutive 0]
So the output is
B = 1 2 3 4 1 2 1 2
1 1 1 2 3 4 1 2
1 1 2 1 1 1 2 1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
The methods I found are all for an array:
For example:
A= [0,0,0,0,1,1,0,0];
i = find(diff(A)) ;
n = [i numel(A)] - [0 i];
c = arrayfun(@(X) 1:X, n , 'un',0);
B = cat(2,c{:})
Output is
B = 1 2 3 4 1 2 1 2
How can I do this for a matrix (without using for)?

Best Answer

A = [0 0 0 0 1 1 0 0;
1 0 1 1 1 1 0 0;
0 1 1 0 1 0 0 1]
m = size(A,1);
B = A';
b = [true(1,m); diff(B)~=0];
[r,~] = find(b);
B(~b) = 1;
B(b) = [1; 1-diff(r)];
B(1,:) = 1;
B = cumsum(B)'