Error using Plot for Fourier Series
3 views (last 30 days)
Show older comments
Hi, I believe I'm close to getting the summation of a Fourier Series plot for different values of N without using add-ons. My code is as follows:
t = [0:0.01:4]; % time grid
n = [1:1:10]; % range of n
x = 0.5 + 2./pi.*sum((-1).^(n-1).*cos(((2.*n)-1)*pi/2.*x'))./(2.*n-1); % summation
% plot
figure;
plot(t, x);
xlabel('t');
ylabel('x');
however, I keep getting an error stating that vectors lengths don't match, but don't see how. If someone could explain, I'd appreciate it.
For context, this is what the series is supposed to look like written out:
0 Comments
Accepted Answer
Star Strider
on 20 Feb 2022
I beleive there is a typographical error in the ‘x’ assignment. I changed the ‘x’ to ‘t’ on the RHS and it works. Also, the summation needs to include the entire expression, so I changed the location of the closing parentheses in the sum call.
t = [0:0.01:4]; % time grid
n = [1:1:10]; % range of n
n = n(:); % Force Column Vector
x = 0.5 + 2./pi.*sum((-1).^(n-1).*cos(((2.*n)-1)*pi/2.*t)./(2.*n-1)); % summation
% plot
figure;
plot(t, x);
xlabel('t');
ylabel('x');
Other that those (and forcing ‘n’ to be a column vector), the code is unchanged.
.
0 Comments
More Answers (2)
Paul
on 20 Feb 2022
Something doesn't look right with x on the left and right hand sides of the equation. Maybe the x on the right hand side should be t, so that the equation reconstructs x(t)? Or, since the closed form equation uses x as the indpendent variable on the rhs, in the code set x = 0:.01:4 and use a different variable on the lhs, like z?
Also, it looks like the argument to the sum() is constructing a matrix with n varying across the columns and x varying down the rows. The sum should be over n, but the actual sum() command defaults to summing down each column. Use the second argument to sum() to tell it to sum across the columns
sum(...., 2)
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!