% Correlation

Tmax = 10000;
t = (0:Tmax);
D = 400; % transmit signal duration
x = sin(2*pi*10*(1:D)/D).*exp(-10*(-D/2:D/2-1).^2/D^2);

figure(1)
plot(x)
title('Transmit signal')

e = zeros(size(t));
T = 5000; % Delay
A = 1; % Amplitude
e(T+1:T+D) = A*x(1:D);
e = e + 0.5*randn(size(t)); % Add noise

figure(2)
plot(t,e)
title('Received signal')

% Compute correlations
R = zeros(Tmax-D,1);
for k=1:Tmax-D
    R(k) = sum(x.*e(k:k+D-1));
end

[rmax,tmax] = max(abs(R));
% adjust for Matlab indexing (starts from 1 instead of 0)
tmax = tmax - 1;
% Convert rmax into estimated a
Aest = rmax/sum(x.*x);

disp(sprintf('Estimated parameters: Aest = %f , Test=%d\n',Aest,tmax));

figure(3)
plot(0:Tmax-D-1,R)
title('Correlation Plot')
grid on
