% Fourier synthesis for square wave
% Prof. Brian L. Evans
% The University of Texas at Austin
% Fall 2017

% Pick a value for the period of x(t)
T0 = 1;
f0 = 1 / T0;
% Pick number of terms for Fourier synthesis
N = 10;
fmax = N * f0;
% Define a sampling rate for plotting
fs = 24 * fmax;
Ts = 1 / fs;
% Define samples in time for one period
t = -0.5*T0 : Ts : 0.5*T0;
% First Fourier synthesis term
a0 = 0.5;
x = a0 * ones(1, length(t));
figure;
plot(t, x);
hold on;
% Generate each pair of synthesis terms
for k = 1 : N
    % Define Fourier coefficients at k and -k
    akpos = (1 - (-1)^k) / (j*2*pi*k);
    akneg = (1 - (-1)^(-k)) / (j*2*pi*(-k));
    theta = j*2*pi*k*f0*t;
    x = x + akpos * exp(theta) + akneg * exp(-theta);
    % Plot Fourier synthesis for indices -k ... k
    plot(t, x);
end
hold off;