Trigonometric Fourier Series of Odd Square Wave
M-file:
%% Filename: TrigFSOddSquareWave.m
% Description: m-file to plot Trigonometric Fourier Series
% representation of odd square wave and its frequency
% (amplitude and phase) spectrum.
clear; clc; close all; % clear memory and command window, close all figures
%% Fourier Series representation of square wave for different numbers
% of terms in summation
t = -3:0.001:3; % times as vector over which to plot FS
Nval = [1, 3, 7, 251]; % number of terms for n in four summations
figure(); % open figure in which to plot truncated Fourier Series
for in = 1:4, % % Build four square waves using increasing number of terms
v = 0; % initialize sum to a_0 = 0
subplot(2,2,in);
% "brute force" plot of true square wave
plot([-3, -3, -2, -2, -1, -1, 0, 0, 1, 1, 2, 2, 3, 3], ...
[ 1, -1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1, 1, -1], ...
'k-.','LineWidth',2);
hold on;
for n = 1:2:Nval(in), % sum over odd values of n
harm = (4/(n*pi))*sin(n*pi*t);
v = v + harm;
plot(t,harm,'b--','LineWidth',1); % plot each harmonic
end
plot(t,v,'r-','LineWidth',2); % plot sum of all terms/harmonics
grid; hold off;
xlabel('time, sec','FontSize',14); ylabel('FS Approx to v(t)','FontSize',14);
title(['Fourier Series Approx w/',num2str(Nval(in)),' Terms'],'FontSize',14);
end
%% Frequency spectrum of Fourier Series
figure(); % open a figure to plot frequency spectrum
n = 1:2:11; % vector of values for n odd noting omega = n x omega_0
a0 = 0; % DC offset
an = 0; % coefficients of cosines
bn = 4./(n*pi); % coefficients of sines for n odd
A = sqrt(an.^2 + bn.^2); % amplitudes
phi = -atan2(bn,an)*180/pi; % phases
% plot amplitude spectrum
subplot(2,1,1); stem([0, n*pi], [a0, A], 'filled'); grid;
xlabel('\omega (rad/sec)'); ylabel('A_n'); title('Amplitude Spectrum');
% plot phase spectrum
subplot(2,1,2); stem([0, n*pi], [0, phi], 'filled'); grid;
xlabel('\omega (rad/sec)'); ylabel('\phi_n'); title('Phase Spectrum');
Plots generated: