The following code should do what you want. There may be some way to do this more elegantly, but I think this works and should be fairly efficient. I haven't thoroughly tested it for all edge cases. If this works for you it would be good to make it into a function that just took the input vector and returned the condensed output.
x = [0 1 0 2 2 3 4 0 0 0 0 7 8 2 2 0 3 0];
xPad = [0 x 0];
startIdx = find(xPad(1:end-1) == 0 & xPad(2:end)~=0);
stopIdx = find(xPad(2:end)==0 & xPad(1:end-1)~=0)-1;
numSegments = length(startIdx);
numZeros = sum(x == 0);
xCond = zeros(1,numSegments + numZeros);
idx = startIdx(1);
for k = 1:numSegments
xCond(idx) = sum(x(startIdx(k):stopIdx(k)));
if k + 1 <= numSegments
idx = idx + (startIdx(k+1) - stopIdx(k));
end
end
Best Answer