Stack Exchange
Weird behavior when accessing matrix during loop
I want to turn some code into a loop, but the results are correct.
This is the original code.
f is just a column matrix of some coefficients that I'm indexing into.
x = 0:pi/100:2*pi;

a1 = f(1) * sin(x);
a2 = a1 + f(2) * sin(3*x);
a3 = a2 + f(3) * sin(5*x);
a4 = a3 + f(4) * sin(7*x);
a5 = a4 + f(5) * sin(9*x);
a6 = a5 + f(6) * sin(11*x);
a7 = a6 + f(7) * sin(13*x);
a8 = a7 + f(8) * sin(15*x);
a9 = a8 + f(9) * sin(17*x);
a10 = a9 + f(10) * sin(19*x);

I have the following code, but it is not producing the same results.
x = 0:pi/100:2*pi;
a = [f(1) * sin(x)];
for n = 2:10
    a = [a; a(n-1) + f(n) * sin((2*n-1) * x)];
end

I have a suspicion that the indexing into the array while I'm creating a new one is causing issues, but I'm not completely sure.
Any tips for debugging this mess would be great.

Does referencing it as a(n-1,:) fix your problem?

You wrote a = [a; a(n-1) + f(n) * sin((2*n-1) * x)]; and a(n-1) only takes one value from a than a row. Therefore, the fix is replacing a(n-1) with a(n-1,:).
x = 0:pi/100:2*pi;
a = [f(1) * sin(x)];
for n = 2:10
    a = [a; a(n-1,:) + f(n) * sin((2*n-1) * x)];
end

yields
0.00    0.03    0.06    0.09    0.13    0.16    0.19 ....
0.00    0.22    0.44    0.65    0.86    1.06    1.26 ....
0.00    0.69    1.36    2.01    2.62    3.19    3.69 ....
0.00    1.56    3.07    4.47    5.71    6.75    7.56 ....
0.00    2.96    5.75    8.22    10.23   11.69   12.52 ....
0.00    4.99    9.57    13.38   16.12   17.61   17.78 ....
0.00    7.77    14.67   19.97   23.11   23.85   22.24 ....
0.00    11.40   21.15   27.87   30.72   29.51   24.71 ....
0.00    15.98   29.03   36.86   38.32   33.59   24.15 ....
0.00    21.60   38.33   46.62   45.16   35.16   19.89 ....

