Complex Fourier Series of Even Triangle Wave

M-file:

%% Filename: ComplexFSEvenTriangleWave.m
% Description: m-file to plot complex (exponential) Fourier Series
% representation of an even triangle wave.

clear all; clc; close all; % clear memory and command window, close all figures
t = linspace(-1.5,3.5,2000); % times over which to plot FS
N = [1, 3, 5, 20]; % upper limit (N) (and lower limit (-N)) for n in summation
c0 = -1/2; % 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*ones(1,length(t)); % initialize summation to c0
    subplot(2,2,in); % open one of four subplots
    % brute force original square wave
    plot([ -1.5, -1, 0, 1, 2,  3,  3.5],...
        [ -0.5, -1, 0,-1, 0, -1, -0.5], 'k-.','LineWidth',2);
    hold on;
    for n = 1:N(in), % loop over different lengths of FS
        fpos = ((1 - cos( n*pi))/(n^2*pi^2))*exp( j*n*pi*t); %compute +n term
        fneg = ((1 - cos(-n*pi))/((-n)^2*pi^2))*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 = -1/2; % DC component (average value)
n  = [-6:-1,1:6]; % values of n for complex spectrum leaving out 0 due to c0 = 0/0
cn = (1 - cos(n*pi))./(n.^2*pi^2); % Fourier coefficients noting 0/0 for n = 0
figure(2); % open figure in which to plot
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 of Even Triangle Wave
Complex Fourier Series of Triangle Wave Spectrum