MATLAB: How to sum up a few numbers in sequence and save as a separate matrix

Image Processing Toolbox

I have a matrix like [0; 0; -1; -2; -1; 0; 0; 0; -2; -1; 0]. From here I would like to sum up sequences of non-zero values and save the result in a separate matrix. From the example, the result should be [-4; -3]. How should I write the code?
Thank you.

Best Answer

Here is an algorithm:
A = [0; 0; -1; -2; -1; 0; 0; 0; -2; -1; 0] % input
B = cumsum(A)
tf = diff([A==0 ; true])==1
C = B(tf)
D = [C(1) ; diff(C)] % output