Complex Fourier Series of Odd Square Wave

M-file:

%% Filename: ComplexFSOddSquareWave.m
% Description: m-file to plot complex (exponential) Fourier Series
% representation of an odd square wave.

clear all; clc; close all; % clear memory and command window, close all figures
t = linspace(-2,3,1000); % times over which to plot FS
N = [2, 4, 6, 100]; % upper limit (N) (and lower limit (-N)) for n in summation
c0 = 0; % DC component (average value)

%% Build complex Fourier Series representation of signal
figure(1); % open figure in which to plot
% Build square wave using increasing number of terms
for in = 1:4, % loop over four different limits (-N,...,N) of Fourier Series
  
  f = c0*zeros(1,length(t)); % initialize summation to c0
  
  subplot(2,2,in); % open one of four subplots
  
  % brute force original square wave
  plot([-2, -1, -1,  0, 0, 1,  1,  2, 2, 3],...
       [ 1,  1, -1, -1, 1, 1, -1, -1, 1, 1],'k-.','LineWidth',2);
  hold on;
  
  for n = 1:1:N(in), % loop over different lengths of FS
    fpos = ((1 - cos( n*pi))/( j*n*pi))*exp( j*n*pi*t); %compute +n term
    fneg = ((1 - cos(-n*pi))/(-j*n*pi))*exp(-j*n*pi*t); %compute -n term
    f    = f + fpos + fneg; % add terms for pos and neg n to series
    
    % plot real terms (harmonics) by adding complex terms for pos and neg n
    plot(t, fpos+fneg, 'b--','LineWidth',1);
  end
  
  plot(t,f,'r-','LineWidth',2); % plot complex FS
  hold off;  
  xlabel('time (sec)', 'FontSize', 14);
  ylabel('Complex FS Approx to f(t)', 'FontSize', 14);
  title(['Fourier Series Approx w/n = ',num2str(-N(in)),', \ldots, ', ...
    num2str(N(in)),' Terms'],'FontSize',14);
end

%% Plot complex frequency spectrum (amplitude and phase) of signal
clear all; % clear memory 
c0 = 0; % DC component (average value)
figure(2); % open figure in which to plot
n  = [-6:-1,1:6]; % values of n for complex spectrum leaving out 0 due to c0 = 0/0
cn = (1 - cos( n*pi))./( j*n*pi); % Fourier coefficients noting 0/0 for n = 0
subplot(2,1,1); % open subplot of amplitude spectrum
stem(0, abs(c0), 'filled', 'LineWidth', 2); % w = 0 component
hold on;
stem(n*pi, abs(cn), 'filled', 'LineWidth', 2); % w = n x pi component
hold off;
xlabel('\omega (rad/sec)', 'FontSize', 14);
ylabel('|c_n|', 'FontSize', 14);
title('Amplitude Spectrum of Complex Fourier Series', 'FontSize', 14);
subplot(2,1,2); % open subplot of phase spectrum
stem(0, angle(c0)*180/pi, 'filled', 'LineWidth', 2); % w = 0 component
hold on;
stem(n*pi, angle(cn)*180/pi, 'filled', 'LineWidth', 2); % w = n x pi component
hold off;
xlabel('\omega (rad/sec)', 'FontSize', 14);
ylabel('\angle c_n (\circ)', 'FontSize', 14);
title('Phase Spectrum of Complex Fourier Series', 'FontSize', 14);

Plots generated:

Complex Fourier Series Representation of Odd Square Wave
Complex Spectrum of Odd Square Wave