%--------------------------------------------------
% Tony Kim
% 6.003: PS#3, Lab
% Note: Here is the basic script. to draw the result
%       for various values of M, I just called this
%       script repeatedly.
%--------------------------------------------------
M = 1000;
N = 4000; % Pick N even. This is the number of points in our time grid

t  = linspace(-1,1,N);
w0 = pi; 
x  = [zeros(1,N/2) ones(1,N/2)];
plot(t,x);
hold on;

% Compute the FFT
a = 1/N*fft(x);

% Curse the Matlab 1-based indexing!
y  = a(1)*ones(1,N);
for k = 1:M
    % Also curse Matlab's convention of using e^(j*w*w0*n) in the
    % analysis equation, rather than _our_ class convention. (This 
    % tripped me up until I read the documentation.)
    y = y + a(k+1)*exp(-j*k*w0*t) + a(N+1-k)*exp(+j*k*w0*t);
end

plot(t,y,'r');