matlab increment addition

Thread Starter

Gerald27

Joined Apr 10, 2012
6
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.
 

MrChips

Joined Oct 2, 2009
30,806
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.
 

Thread Starter

Gerald27

Joined Apr 10, 2012
6
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

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.
 

MrChips

Joined Oct 2, 2009
30,806
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.
 

Thread Starter

Gerald27

Joined Apr 10, 2012
6
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

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.
 

MrChips

Joined Oct 2, 2009
30,806
A = [ 5 6 7 8]

C = diff(A)

B = [ 4 5 6 ]

D = B.*C

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

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

Thread Starter

Gerald27

Joined Apr 10, 2012
6
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


A = [ 5 6 7 8]

C = diff(A)

B = [ 4 5 6 ]

D = B.*C

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

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

MrChips

Joined Oct 2, 2009
30,806
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.
 
Top