In this tutorial, we will write Fourier series of a simple function using Matlab.

Let’s assume we have a square wave with following characteristics:

$\begin{align} & Period=2ms \\ & Peak-to-Peak\text{ }Value=2\text{ }V \\ & Average\text{ }Value=0\text{ }V \\\end{align}$

So, we can express it as:

\[\begin{align} & x(t)=\frac{4}{\pi }\sum\limits_{n=1}^{\infty }{\frac{1}{(2n-1)}\sin \left[ (2n-1)2\pi {{f}_{o}}t \right]}\text{ }\cdots \text{ }(1)\text{ } \\ & and\text{ }assume \\ & {{f}_{0}}=500Hz \\\end{align}\]

If g(t) is given by

$g(t)=\frac{4}{\pi }\sum\limits_{n=1}^{12}{\frac{1}{(2n-1)}\sin \left[ (2n-1)2\pi {{f}_{o}}t \right]}\text{ }\cdots \text{ }(2)\text{ }$

Now, we will write a Matlab code for g(t) between 0 and 4ms with an interval of 0.05 ms to demonstrate that g(t) is a decent approximation of original function x(t).

% Fourier Series Expansion for Square Wave
%% Parameters as mentioned in text
f = 500; % Frequecny
C = 4/pi; % Constant Value
dt = 5.0e-05; % Interval between teo time steps
tpts = (4.0e-3/5.0e-5) + 1; % Total points "(final point-initial point)/Interval+1%
for n = 1: 12 % Values we are considering to approximate Fourier Seires instead of infinity as given in original function x(t)
for m = 1: tpts % Here, we'll consider all "t" points to cover "from 0 to 4ms interval"
s1(n,m) = (4/pi)*(1/(2*n - 1))*sin((2*n - 1)*2*pi*f*dt*(m-1)); % Approximate Fourier Series g(t)
end
end
for m = 1:tpts
a1 = s1(:,m); % VERY IMPORTANT ! Here, we are assigning a1 for each single column (total 81)
a2(m) = sum(a1); % Here, we are summing up the whole column to one single value (adding all 12 values in one column)
end
% Now, we have a row vector "a2" with total values "81"
f1 = a2'; % Here, we have final values "f1" (total 81 points) as transpose of a2 computed above
t = 0.0:5.0e-5:4.0e-3; % it's already given in text (0 to 4ms with interval of 0.05 ms)
%% Plotting results
plot(t,f1)
xlabel('Time, s')
ylabel('Amplitude, V')
title('Fourier Series Expansion')

**Results:**

## Fig. 1: Fourier Series of Square Wave