MATLAB: How to add particular elements in a vector based on some condition in a loop fashion

addition of particular vector elements based on certain conditions

I have two vectors L and Z of length 'n' and 'n-1'. for ex:L=[L1 L2 -L3 L4 -L5 L6 L7 -L8 L9 L10] & Z=[Z1 Z2 Z3 Z4 Z5 Z6 Z7 Z8 Z9] starting from last element to first of vector L i.e L10, L9…. L1 if L is negative i.e first negative is -L8 add Z8+Z9 i.e elements between -L8 to end which are z8,z9 Look for next negative element of L i.e -L5 add Z5+Z6+Z7 i.e elements between -L5 and -L8 which are z6,z6,z7 look for next negative element of L i.e -L3 add Z3+Z4 i.e between -L3 and -L5 which are z3,z4 and finally add Z1+Z2 i.e between -L3 and starting point which are z1,z2…
this should continue in loop passion and finally my new vector(NV) should look like NV=[Z1+Z2, Z3+Z4, Z5+Z6+Z7,Z8+Z9]
Please do the needful thank you

Best Answer

Using vectorized code will be a much neater solution than using a loop. Try something like this:
>> L = [1,2,-3,4,-5,6,7,-8,9,10];
>> Z = 1:9;
>> X = cumsum([true;diff(sign(L(:)))<0]);
>> accumarray(X(1:numel(Z)),Z)
ans =
3
7
18
17
Where sum(Z(1:2))==3, sum(Z(3:5))==7, etc.