% Problem 4.10.

h = [1, -1, -1, 1, 1, -1, 1];
s = fliplr(h);			% Signal is time-reversed impulse response

v = [0.14 0.48 1.61 2.09 -2.4 0.4 2.35 -0.59 -1.81 0.32 -0.47 1.81 -1.63 -2.28];
t = 0:13;

rsv = xcorr(s, v);
N = length(rsv);
l = -(N-1)/2:(N-1)/2;
figure(1)
subplot(211)
plot(l, rsv);
title('xcorr(signal, received waveform)')
xlabel('Lag (usec)')
ax=axis;
axis([l(1) l(N) ax(3) ax(4)]);

% Pass received signal through matched filter

y = conv(v, h);
Ny = length(y);
subplot(212)
plot(0:Ny-1, y);
xlabel('Time (usec)')
title('Output of matched filter')
ax = axis;
axis([0 Ny-1 ax(3) ax(4)]);

figure(2)
Ns = length(s);
subplot(211)
plot(0:Ns-1, s*1.5);
title('Signal')
xlabel('Time (usec)')
subplot(212)
Nv = length(v);
plot(0:Nv-1, v);
xlabel('Time (usec)')
title('Noisy signal')

% To estimate matched filter constant from data:

ns = v(4:10);
nn = [v(1:3), v(11:Nv)];

c = sqrt( (s*s') / ((ns*ns') - (nn*nn')) )
