Fourier series code gives the wrong plot
6 views (last 30 days)
Show older comments
Hello everyone and Happy new year,
I am trying to plot some functions and their fourier series but my code gives me the same looking plot for everything,
i searched the community and i cant figure out what is wrong with this code
And is it function or code?!
Please help and Thank you

2 Comments
Answers (1)
Anay
on 1 Apr 2025
Edited: Anay
on 1 Apr 2025
Hi Kamyar,
From the code you have provided in comments, I understand that you're trying to plot a piecewise function and its Fourier series approximation. There are a few issues in your code which is causing the unexpected output.
- You must use the factor “1/pi” for the coefficients “a_0”, “a_n” and “b_n” for their correct computation.
- The code is not accumulating Fourier terms. The line, "f=(a(n)*cos(n*x))+(b(n)*sin(n*x));", simply overrides the Fourier terms instead of storing them or accumulating them.
- The range of the plot must be set correctly to [-pi, pi] to match the interval of integration.
You can refer to the following code which highlights all the above points:
clear; clc;
syms x n
% Define the piecewise function
y = piecewise(x < 2, sin(x), x > 2, sin(2*x), nan);
% Calculate the Fourier series coefficients
a0 = (1/pi) * int(y, x, -pi, pi);
a = sym(zeros(1, 10));
b = sym(zeros(1, 10));
for n = 1:10
a(n) = (1/pi) * int(y * cos(n * x), x, -pi, pi);
b(n) = (1/pi) * int(y * sin(n * x), x, -pi, pi);
end
% Accumulate the Fourier terms
fu = a0 / 2;
for n = 1:10
fu = fu + a(n) * cos(n * x) + b(n) * sin(n * x);
end
% Set the correct range to plot the functions
fplot(y, [-pi, pi], 'LineWidth', 1.5);
hold on;
fplot(fu, [-pi, pi], 'LineWidth', 1.5);
legend('Original Function', 'Fourier Series Approximation');
title('Piecewise Function and its Fourier Series');
xlabel('x');
ylabel('y');
grid on;
I hope this addresses the issue!
0 Comments
See Also
Categories
Find more on Calculus in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!