How do I save each value for this loop?

N = 5;
A = 0;
w = 1; %where omega is equals to 2pi/tau and tau is equals to 2pi
a_0 = pi/4;
for i = 1:1:N
a_n = 2*(-1)^N-1 / pi*N^2;
A(i) = A + a_n;
end
I'm trying to make a fourier series code and this is part of it. I'm trying to save each value I get from that for loop and use it later for the calculation and plotting. My problem is that whenever I run this, I get an error message saying
In an assignment A(:) = B, the number of elements in A and B must be the same.
Error in test (line 9)
A(i) = A + a_n;
So as far as I understand, The first loop is going to be okay because A(1) will be a value of A+a_n, which is a sum of scalar, but from second loop, variable A becomes vector but a_n is still scalar so it's causing this error.
How do I solve this error and make it run?

 Accepted Answer

I am not certain what you want.
Try this:
N = 5;
A = 0;
w = 1; %where omega is equals to 2pi/tau and tau is equals to 2pi
a_0 = pi/4;
for i = 1:1:N
a_n = 2*(-1)^N-1 / pi*N^2;
A(i+1) = A(i) + a_n;
end

6 Comments

Hi Thanks fr the answer!
so what I'm trying to do is make is a loop that the value stacks up as it loops. So what I'm expecting to see is similar to this. Note that A(i) for this means the last value of that vector. For eg. if a_n is 1, A(1) is going to be 1, A(2) is going to be 2, A(3) 3 and so on... and at the end A(5) becomes 5 and this needs to have a vector of [1 2 3 4 5]
A(1) = a_n
A(2) = A(1) + a_n
A(3) = A(2) + a_n
A(4) = A(3) + a_n
A(5) = A(4) + a_n
My code should do exactly that, with this slight change:
N = 5;
A = 0;
w = 1; %where omega is equals to 2pi/tau and tau is equals to 2pi
a_0 = pi/4;
a_n = 2*(-1)^N-1 / pi*N^2;
A(1) = a_n;
for i = 1:1:N
A(i+1) = A(i) + a_n;
end
Since ‘a_n’ is independent of the loop index, there is no reason to evaluate it in the loop.
Note that you can avoid the loop entirely with:
A = a_n * (1:N+1);
Experiment to get the result you want.
Thanks!
I was touching this and that to the code and modified little bit.
N = 5;
a_n = ( 2*(-1)^(N-1) ) / (pi*N^2);
A = 0;
B = 0;
w = 1; %where omega is equals to 2pi/tau and tau is equals to 2pi
a_0 = pi/4;
for i = 1:1:N
A(i+1) = A(i) + a_n
end
But the result isn't what I expected because it creates matrix with 6 vectors
A =
0 0.0255 0.0509 0.0764 0.1019 0.1273
I guess this is happening because A(i+1) is equals to A(2).
If I remove +1 from A(i+1) it gives this error
Index exceeds matrix dimensions.
Error in test (line 9)
A(i) = A(i) + a_n
Do this instead:
A = a_n * (1:N+1);
Thanks for the help! It seems to be working :)
As always, my pleasure!

Sign in to comment.

More Answers (0)

Categories

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

Products

Tags

Community Treasure Hunt

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

Start Hunting!