Fourier series code gives the wrong plot

6 views (last 30 days)
Kamyar D
Kamyar D on 1 Jan 2021
Edited: Anay on 1 Apr 2025
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
KALYAN ACHARJYA
KALYAN ACHARJYA on 1 Jan 2021
Please share the code within the text body (Insert code, Alt+Enter)
Kamyar D
Kamyar D on 2 Jan 2021
Thank you, here it is:
clear;clc;
syms x n
y = piecewise(x < 2, sin(x), x > 2, sin(2*x) , nan);
a0=(1/2)*int(y,x,-pi,pi);
for n=1:10
a(n)=(1/2)*(int(y*cos(n*x),x,-pi,pi));
b(n)=(1/2)*(int(y*sin(n*x),x,-pi,pi));
f=(a(n)*cos(n*x))+(b(n)*sin(n*x));
end
fu=(a0/2)+sum(f);
fplot(x,y);
hold on;
fplot(x,fu);
! I tried this code too and resaults are the same:
clear;clc;
syms x n
L=2;
y = piecewise( x < L, sin(x), x > L , sin(2*x) , nan);
a0=(1/L)*int(y,x,-L,L);
for n=1:10
an=(1/L)*(int(y*cos((n*pi/L)*x),x,-L,L));
bn=(1/L)*(int(y*sin((n*pi/L)*x),x,-L,L));
f=(an*cos((n*pi/L)*x))+(bn*sin((n*pi/L)*x));
end
fu=(a0/2)+sum(f);
fplot(x,y);
hold on;
fplot(x,fu);

Sign in to comment.

Answers (1)

Anay
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.
  1. You must use the factor “1/pi” for the coefficients “a_0”, “a_n” and “b_n” for their correct computation.
  2. 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.
  3. 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!

Community Treasure Hunt

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

Start Hunting!