% Assignment NO. 01;

% Question 5:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

clear
clc

% 8000 samples, from 0 to 7999
n = 0:1/8000:1-(1/8000);
% Input sequence, sum of three cosines with three frequencies, 0.5Khz,
% 1.5KHz, and 3.5KHz.
x = 3 * cos((2 * pi * 500) * n) + 2 * cos((2 * pi * 1500) * n) ...
    - 2 * cos((2 * pi * 3500) * n);

% Plotting the input sequnece against the index n
stem(n, x);
axis([0 0.005 -10 10]);
xlabel('n');
ylabel('x[n]');
title('x[n] vs. n');
figure

% Implementing the moving average system.
%-----------------------------------------
% y(n) = (1/(m1 + m2 + 1)) * partialSum;
% partialSum = sum of elements in window
% * m1 is the lower limit of the window size
% * m2 is the upper limit of the window size
% * partialSum holds the sum of the elements 
%   of input sequence in the window
m1 = 1;
m2 = 5;
partialSum = 0;

% Loops to slide window over the elements of the input sequence
for i = 1:(8000 - (m2 - m1 + 1))
    % Slicing the input sequence by the moving window
    subx = x((m1 + i):(m2 + i));
    % Summing the elements of the window
    partialSum = sum(subx);
    % Applying the moving average formula to partialSum
    y(i) = (1/(m1 + m2 + 1)) * partialSum;
end

% Plotting the output sequence against the index n
ind = 0:1/8000:1;
stem(ind(1:length(y)), y);
max(y)
axis([0 0.01 -5 5]);
xlabel('n');
ylabel('y[n]');
title('y[n] vs. n');
figure

% Calculating the FFT of the output sequence to plot the
% amplitude spectrum.
frequencySpectrum = fft(y);
amplitudeSpectrum = abs(frequencySpectrum);
stem(n(1:length(y)), amplitudeSpectrum);
xlabel('f');
ylabel('amplitude');
title('amplitude of y[n] vs. f');
max(amplitudeSpectrum)