MATLAB: Adding next values in an array

arrays

hi all, I have a question
I have a vector like this [1;2;3;-5;-6;2;3], when it's negative i would like to add in the next value and get something like that [1;2;3;-5;-11;-9;-6]. Which means when it's negative it starts adding the next value!
the thing is that i have an array with 48×258 dimensions, so the example above would be for each column!
thanks a lot!

Best Answer

M = [1 2 3 -5 -6 2 3]' %demo data
M + cumsum([zeros(1, size(M, 2)); M(1:end-1, :)] .* (cumsum(M<0, 1)>1), 1)
Will do what you want on any sized matrix.
Explanation of above code:
  1. M<0 finds sign of M
  2. cumsum(M<0, 1) will be 1 or more at the first negative value in each column
  3. cumsum(M<0, 1)>1 will be one after the first negative value all the way down
  4. [zeros(1, size(M, 2)); M(1:end-1, :)] is M shifted down by one row
  5. 4.*5 filters the shifted M so that all positive values before the first negative values are 0 AND the first negative value is 0
  6. cumsum of 6 + M is the desired result