MATLAB: Finding Consecutive True Values in a Vector

findlogical?

I want to sum consecutive 1 values given a logical input vector. An example of input and output is below. Notice that the output is the sum of the previous elements that were 1 and if a zero element is encountered, the sum starts over. I am trying to avoid a for loop here if I can. Suggestions?
Input Output
0 0
0 0
0 0
1 1
0 0
1 1
0 0
0 0
1 1
1 2
1 3
1 4
0 0
1 1
0 0
1 1
1 2
0 0

Best Answer

a0 = a(:); % input vector
ii = strfind(a0',[1 0]);
a1 = cumsum(a0);
i1 = a1(ii);
a0(ii+1) = -[i1(1);diff(i1)];
out = cumsum(a0); % output vector