How to plot Fourier series for function in a right way?

4 views (last 30 days)
if true
% code
a=[0,pi/2,pi/2,pi];
b=[0,-1,0,0];
plot(a,b)
hold on
n=50;
ao=-pi/4;
T=[0,pi,0,1];
for i=1:length(T)
t=linspace(a(i),b(i));
end
suma=0;
for i=1:n
bn=cos(pi*i)/2/i;
an=(1-cos(pi*i))/4/(i)^2;
suma=suma+(bn.*sin(2.*i.*t))+(an.*cos(2.*i.*t));
end
series=ao/2+suma;
plot(t,series)
hold off
end

Accepted Answer

Torsten
Torsten on 5 Nov 2018
Edited: Torsten on 5 Nov 2018
f=@(x)-2/pi*x.*(x>=0 & x<=pi/2)-2*(x/pi+1).*(x>=-pi & x<=-pi/2);
n=50;
k=0:n;
a=1/pi*(integral(@(x)f(x).*cos(k*x),-pi,-pi/2,'ArrayValued',true)+integral(@(x)f(x).*cos(k*x),0,pi/2,'ArrayValued',true));
k=1:n;
b=1/pi*(integral(@(x)f(x).*sin(k*x),-pi,-pi/2,'ArrayValued',true)+integral(@(x)f(x).*sin(k*x),0,pi/2,'ArrayValued',true));
ffun=@(x)a(1)/2+sum(a(2:n+1).*cos((1:n)*x)+b(1:n).*sin((1:n)*x));
x=linspace(0,pi,200);
fx=arrayfun(@(x)ffun(x),x);
plot(x,fx,x,f(x))

More Answers (0)

Community Treasure Hunt

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

Start Hunting!