# matlab increment addition

Discussion in 'Programmer's Corner' started by Gerald27, Apr 11, 2012.

1. ### Gerald27 Thread Starter New Member

Apr 10, 2012
6
0
A= [5 6 7 8]
B= [4 5 6 7]
for i=1:4,
C(i) = A(i+1) - A(i)
D(i) = C(i)*B(i)
E(i) = D(i+1) + D(i)
end
can anybody help me with this code
every time i get a value for D i want to add them to the previous value of D but i am getting an error
Attempted to access D(2); index out of bounds because numel(D)=1.

2. ### MrChips Moderator

Oct 2, 2009
12,622
3,451
You have two problems.

Firstly, why not create D with initial values of 0?

D = [ 0 0 0 0 ]

Secondly, A(i+1) and D(i+1) will both cause an error when i = 4.

3. ### Gerald27 Thread Starter New Member

Apr 10, 2012
6
0
D = [ 0 0 0 0 ]
A= [5 6 7 8]
B= [4 5 6 7]
for i=1:4,
C(i) = A(i+1) - A(i)
D(i) = C(i)*B(i)
E(i) = sum(D(i))
end

i initialize d with zero but thats not my problem
the value of E should equal the sum of the increment of D but it keep giving me the the value of D but not adding them

4. ### MrChips Moderator

Oct 2, 2009
12,622
3,451
I have no idea what you are talking about.
What do you mean by "the increment of D"?
And after you answer that, what do you mean by "the sum of the increment of D"?

Also remember that MATLAB's strength is in matrix arithmetic. You may not need a for-loop.

5. ### Gerald27 Thread Starter New Member

Apr 10, 2012
6
0
D = [ 0 0 0 0 ]
A= [5 6 7 8]
B= [4 5 6 7]
for i=1:4,
C(i) = A(i+1) - A(i)
D(i) = C(i)*B(i)
E(i) = sum(D(i))
end

thats the results i should get at the end
C=[1 1 1]
D=[4 5 6]
E=[11 15]

for example i have this value D=[1 2 3 4 5 6 7 8 9]
i want to get E=[1+2=3 3+3=6 6+4=10 10+5=15 15+6=21 21+7=28 28+8=32]
so E=[3 6 10 15 21 28 32] thats what i was trying to say

6. ### MrChips Moderator

Oct 2, 2009
12,622
3,451
A = [ 5 6 7 8]

C = diff(A)

B = [ 4 5 6 ]

D = B.*C

C=[1 1 1]
D=[4 5 6]
E=[11 15]

is not consistent with the second example.
Should it be E = [9 15] ?

7. ### Gerald27 Thread Starter New Member

Apr 10, 2012
6
0
yes it should be E = [9 15], typing error, but when i do E= sum(D(i)) i get E=[4 5 6] it return the same value i receive for D

8. ### MrChips Moderator

Oct 2, 2009
12,622
3,451
E = cumsum(D)

Gerald27 likes this.
9. ### Gerald27 Thread Starter New Member

Apr 10, 2012
6
0
yes thats the function i been looking for
thank you

10. ### MrChips Moderator

Oct 2, 2009
12,622
3,451
You're welcome. Don't be afraid to use the Help menu.
In this case searching for diff and sum would lead you to the proper functions.