% Problem 4.11

x = [1 1 -1 1 -1 -1 1 -1];
y = [0 0 0.5 1.5 1.5 1.5 1 -1 -1 -1 -1.5 -0.5 -0.5 -0.5];

Nx = length(x);

rxy = xcorr(x, y);
Nr = length(rxy);
l = -(Nr-1)/2:(Nr-1)/2;
z = find(l >= 0);

h = rxy(z)/Nx;
j = l(z);

figure(1)
clg
subplot(211)
plot(j, h);
title('Impulse response')
ax=axis;
axis([j(1) j(length(j)) ax(3) ax(4)]);

y1 = conv(x, h);
N1 = length(y1);
Ny = length(y);
subplot(212)
plot(0:N1-1, y1, '-', 0:Ny-1, y, ':');
title('Estimated vs. actual output')
legend('Estimated', 'Actual')
ax=axis;
axis([0 N1-1 ax(3) ax(4)]);

figure(2)
clg
rxx = xcorr(x,x);
Nxx = length(rxx);
plot(-(Nxx-1)/2:(Nxx-1)/2, rxx)
title('Autocorrelation of PN sequence')
ax=axis;
axis([ -(Nxx-1)/2 (Nxx-1)/2 ax(3) ax(4)]);
