How to accumulate values into a variable using for loops?

Hello,
I have an array that contains 1597 values. Let's call that X. I want to create a second array, Y, that should act as the following:
Y(1) = (X(1) + X(2))/(constant)
Y(2) = (X(2) + X(3))/(constant) + Y(1)
Y(3) = (X(3) + X(4))/(constant) + Y(2)
Y(4) = (X(4) + X(5))/(constant) + Y(3)
..and so on, until the last one:
Y(1596) = (X(1596) + X(1597))/(const) + Y(1595)
My code, which does not return an error, but also does not produce the correct values for Y, is as follows:
Y = zeros(1,length(X)-1);
Y(1) = (X(1)+X(2))/(constant);
i = 1:length(X);
for c = 1:length(X)-2
Y(c+1) = (X(c+1)+X(c+2))/(constant) + Y(i(c));
end
As stated above, the results I'm getting are not accurate (I'm comparing with results obtained through Excel, which are definitely correct). If anyone can please tell me where I'm going wrong, I would greatly appreciate it. If this description isn't clear enough, please let me know and I will try to clarify. Any help is greatly appreciated.
Thanks.

 Akzeptierte Antwort

Yao Li
Yao Li am 16 Apr. 2013
Bearbeitet: Yao Li am 16 Apr. 2013
Y(c+1) = (X(c+1)+X(c+2))/(constant) + Y(c);
Also, actually, you don't need the parameter i.

3 Kommentare

NH
NH am 16 Apr. 2013
Ah, that's true. Thanks for pointing that out. It turns out, however, that I was doing it correctly. Even though the parameter i was unneeded, it still gave me the same answers as yours gave. This is still problematic because the answers produced from Matlab don't match the values produced from Excel. Could this be because of different significant figures used in each program? I am dealing with numbers of 10^-12 degree...
I think the output of Matlab shoulb be close to that of Excel, but the precisions are different. Maybe you can try other data format in Matlab or Excel since the value are too small. It's better to give an example to show the differences.
NH
NH am 16 Apr. 2013
Problem solved. Careless mistake: started reading original values at wrong point, causing a slight offset. Thanks for your help and patience.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Tags

Gefragt:

NH
am 16 Apr. 2013

Community Treasure Hunt

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

Start Hunting!

Translated by