%% Cell 1
% EXAMPLE 1: Plot the autocorrelation sequence of a sinewave with frequency 
% 1 Hz and sampling frequency of 200 Hz
N=1024; % Number of samples
f1=1; % Frequency of the sinewave
FS=200; % Sampling Frequency
n=0:N-1; % Sample index numbers
x=sin(2*pi*f1*n/FS); % Generate the signal, x(n)
t=[1:N]*(1/FS); % Prepare a time axis
subplot(2,1,1); % Prepare the figure
plot(t,x); % Plot x(n)
title('Sinwave of frequency 1000Hz [FS=8000Hz]');
xlabel('Time, [s]');
ylabel('Amplitude');
grid;
Rxx=xcorr(x); % Estimate its autocorrelation
subplot(2,1,2); % Prepare the figure
plot(Rxx); % Plot the autocorrelation
grid;
title('Autocorrelation function of the sinewave');
xlable('lags');
ylabel('Autocorrelation');
% Note that when using the function xcorr, to estimate the autocorrelation 
% sequence, it has double the number of samples as the signal x(n). An important 
% point to remember when using the function xcorr is that the origin is in 
% the middle of the figure (in the above example, it is at lag=1024)



% You can write your own version of autocorrelation function for discrete
% data sets:
%function [Rxx]=autom(x) %Save this function as autom.m
% Input variable is a vector x containing signal of length N
% Output is autocorrelation vector Rxx 
%N=length(x); % find the number of elements in the input signal
%average_x=mean(x); % find average value of x
%Rxx=zeros(1,N); % store zeros in the output Rxx vector
%for m=1: N+1
%    for n=1: N-m+1
%        Rxx(m)=Rxx(m)+(x(n)-average_x)*(x(n+m-1)-average_x);
%    end;
%end;
%end



%% Cell 2
% EXAMPLE 2: Repeat Example 1 using manually coded function autom(x) 
N=1024;
f1=1;
FS=200;
n=0:N-1;
x=sin(2*pi*f1*n/FS);
t=[1:N]*(1/FS);
subplot(2,1,1);
plot(t,x);
title('Sinwave of frequency 1000Hz [FS=8000Hz]');
xlabel('Time, [s]');
ylabel('Amplitude');
grid;
Rxx=autom(x);
subplot(2,1,2);
plot(Rxx);
grid;
title('Autocorrelation function of the sinewave');
xlabel('lags');
ylabel('Autocorrelation');
% Note that using Rxx to estimate the autocorrelation function generates 
% the same number of samples as the signal itself and that the maximum is 
% now placed at the origin [that is, Rxx(1) is the origin]



%% Cell 3
% EXAMPLE 3: Why is autocorrelation useful - finding signal within apparent noise
% Plot autocorrealtion of the following signal 
% x(n)=sin(2*pi*f*t) with f=1 Hz
% y(n)=x(n) + w(n)
% where w(n) is a zeros mean, unit variance Gaussian random process
N=1024; % Number of samples to generate
f=1; % Frequency of the sinewave
FS=200; % Sampling frequency
n=0:N-1; % Sampling index
x=sin(2*pi*f1*n/FS); % Generate x(n)
y=x+2*randn(1,N); % Generate y(n) where you can increase amplitude in front 
% of randn in order to reduce signal-to-noise ratio
subplot(3,1,1);
plot(x);
title('Pure Sinewave');
grid;
subplot(3,1,2);
plot(y);
title('y(n), Pure Sinewave + Noise');
grid;
Rxy=xcorr(y); % Estimate the autocorrelation
subplot(3,1,3);
plot(Rxy);
title('Autocorrelation Rxx');
grid;

