% Plot the truncated exponential Fourier series of the triangle wave
% on page 198 of the Lathi text.
%
% ELEC 320, Rich Kozick
%

N = input('Number of harmonics: ');

t = -0.5:6/1000:1.5;  % Time values to evaluate function: 
T = 2;		  % Period
w0 = 2*pi/T;	  % Fundamental frequency

D0 = 0.0;
xN = D0*ones(1,length(t));   % dc component

% Compute truncated exponential Fourier series

clear D
A = 1;  % Amplitude of triangle wave
for n=1:N
  D(n) = -j*4*A/(pi*n)^2 * sin(n*pi/2);
  xN = xN + D(n)*exp(j*n*w0*t) + conj(D(n))*exp(-j*n*w0*t);
end

% Define the triangle wave
g = zeros(size(t));
z1 = find(abs(t) <= 0.5);
z2 = find((abs(t-1) <= 0.5));
g(z1) = 2*A*t(z1);
g(z2) = -2*A*(t(z2)-1);

figure(1)
subplot(211)
stem((0:N)*w0, 2*abs([D0, D]))
xlabel('FREQUENCY (rad/sec)')
ylabel('C_n')
title('ONE-SIDED MAGNITUDE SPECTRUM')
subplot(212)
plot(t,xN)
plot(t,xN, 'b-', t, g, 'r-')
legend('FS APPROX.', 'SIGNAL');
title(['Triangle wave with harmonics <= ',num2str(N)])
xlabel('Time (sec)')
ylabel(['x',num2str(N),'(t)'])
axis([-0.5 1.5 -1.1 1.1])


