<

# MATLAB tutorial 2.5: Square wave functions

Fourier Series


%Complex Fourier Series Example: Piecewise Step Function
%First, plot the piecewise function which is equal to 1 from (-2,-1), to 0
%from (-1,0) and to 2 from (0,2)
syms x
y = piecewise(-2<x<-1,2,-1<x<0,0,0<x<2,-1)
figure(1)
fplot(y)
ylim([-2,3])
%with the coefficients of the fourier series already given, plot the
%fourier series of the piecewise function and compare the approximation for
%about 10 to 50 terms approximately
k=(1:100);
t=linspace(0,2*pi,500);
[K,T] = ndgrid(k,t);
sys = @(k,t) 5/400-1./(k.*pi).*sin(k.*pi./2).*cos(-k.*pi.*t./2)+(1./(k.*pi).*((-1).^k-2+cos(k.*pi./2))).*sin(-k.*pi.*t./2);
sys_sum = sum(sys(K,T));
figure(2)
plot(t,sys_sum)



%Fourier Series for a periodic Pulse Function ex1%
%i)First plot the piecewise function the heavyside function which is a
%pulse function that is H = 1 from x = 0 to x = h, and H = 0 from x=h to
%x=T, h is the pulsewidth and T is the period.%
syms x
y = piecewise(-5<x<-3,0,-3<x<-1,1,-1<x<1,0,1<x<3,1,3<x<5,0);
figure(1)
fplot(y)
xlim([-6,6])
ylim([-1,2])
%ii)Next solve for the fourier coefficients by integrating the cosine and
%sine functions given which will approximate a,a1,b1
syms x
p =@(x,n) cos(n.*x.*2*pi/3)
q =@(x,n) sin(n.*x.*2*pi/3)
a0 = 2/3
a1 = (2/3)*int(p,x,[0,1])
b1 = (2/3)*int(q,x,[0,1])
%iii)finally using the fourier coefficients wrtie the fourier series and
%graph the function comparing the approximation to the piecewise function
n=(1:100);
x=linspace(0,2*pi,1000);
[N,X] = ndgrid(n,x);
a0 = 2/3;
sys = @(n,x) a0./200 +((sin(2.*pi.*n./3))./(pi.*n).*cos(n.*x*2.*pi./3))+ (2.*((sin(pi.*n./3)).^2)./(pi.*n).*sin(n.*x.*2.*pi./3));
sys_sum = sum(sys(N,X));
figure(2)
plot(x,sys_sum)