MATLAB tutorial 2.5: Fourier Series

Fourier Series


Examples of Fourier Series Square Wave Functions part1%
%i)the example involves graphing three similar heaviside square wqave
%functions, that only differ by a shift. The 3 functions are f,g, and h.
%For the l selected it will be l=1, so function f will equal 1 from (0,1)
%and -1 from (1,2), then g will equal 1 from (0,1) and 0 from (1,2) and h
%will equal 0 from (0,1) and 1 from (1,2)
%To find the fourier series of each function, you will have to find the
%coefficients which for f is different than the other two but g and h share them in common. They must be solved by
%integration of the their function values in a product with cosine and sine
%functions.
%For f(x) the a0 and a1 term are both 0 since f is an odd function. So we
%only need to solve for b1%
syms x
p =@(x,k) sin(k.*x*pi)
b1 = int(p,x,[0,2])
%ii)Using the b1 coefficient found for f, we write the fourier series of f
%and plot it from 0 to 2%
l=1
n=(1:100);
x=linspace(0,2*pi,100);
[N,X] = ndgrid(n,x);
sys = @(n,x) 4.*l./pi.*(1./(2.*n+1).*sin((2.*n+1).*pi.*x./l))   ;
sys_sum = sum(sys(N,X));
plot(x,sys_sum);


%Examples of Fourier Series Square Wave Functions ex2%
%i)Find the coefficients of function g, wihch shares the same as h, by
%using integration of their function from 0 to 2. the integration will be
%a product of a cosin or sine function and the functions themself. The
%coefficients we will find are a0,a1, and b1
syms x
p =@(x,k) cos(k.*x*pi)
q =@(x,k) sin(k.*x*pi)
a0 = 0.50*(int(1,x,[0,2]))
a1 = int(p,x,[0,2])
b1 = int(q,x,[0,2])

%We use the coefficients to plot the fourier series of the g function%
l=1
n=(1:100);
x=linspace(0,2*pi,100);
[N,X] = ndgrid(n,x);
sys = @(n,x) (1/200) + 2.*l./pi.*(1./(2.*n+1).*sin((2.*n+1)*pi.*x./l))
sys_sum = sum(sys(N,X));
plot(x,sys_sum)


%Finally, we also plot the fourier series of the h function using the
%coefficients of a0, a1, and b1 calculated%
l=1
n=(1:100);
x=linspace(0,2*pi,100);
[N,X] = ndgrid(n,x);
sys = @(n,x) (1/200) -2.*l./pi.*(1./(2.*n+1).*sin((2.*n+1)*pi.*x./l))   ;
sys_sum = sum(sys(N,X));
plot(x,sys_sum);


%Gibbs Phenomenon Continuous Piecewise Function Example%
%i)Plot a piecewise function which for f(x) equals 0 from x=-pi to x=0 and
%where f(x) = x from x=0 to x=pi
syms x
y = piecewise(-pi