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

1 view (last 30 days)
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

Accepted Answer

Stephen23
Stephen23 on 5 Feb 2015
Edited: Stephen23 on 5 Feb 2015
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.
  1 Comment
Raghavendra Reddy P
Raghavendra Reddy P on 5 Feb 2015
Thank you.. This is the great response.If it works without loops its really cool. as per your response, it sums cumulatively when sign changes from + to - and vice-versa, but for my problem starting from last element of L, i want sum between end element to 1st negative element, then between 1st negative to 2nd negative, 2nd negative to 3rd negative,....., last negative to starting point. In your response it will sums between + and - & vice-versa, I want sum between two negative numbers. for this example your code gives >> 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
12
21
9
1+2==3 its right, 3+4+5==12 it is also right, next it should be equal to 6 coz sum between -L6 and -L7 is Z6==6, next sum between -L7 and -L9 is Z7+Z8=7+8==15, next between -L9 and end element L10 is Z9==9.... so final ans should look like ans =
3
12
6
15
9

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!