function R=corrviz(X,Y)
% corrviz(X,Y)  Visualize correlation
%   X and Y are two vectors.  Calculat rxy, their cross-correlation,
%   one point at a time, showing the alignment of the two sequences, 
%   sliding X over Y.
% 2000-09-19 dpwe@ee.columbia.edu

Nx = length(X);
Ny = length(Y);
Nr = Nx+Ny-1;

xmin = -(Nx - 1);
xmax = Ny + Nx - 1;

subplot(311)
plot(0:(Ny-1),Y);
ax = axis;
axis([xmin,xmax, ax(3), ax(4)]);
grid on;
title('Y[n]')

R = nan*ones(1,Nr);
% Precalculate vertical limits of correlation output
axr = [xmin,xmax, min(xcorr(X,Y)), max(xcorr(X,Y))];

% Make a version of y padded to the full extent of X's we'll shift
padY = [zeros(1,Nx-1),Y,zeros(1,Nx-1)];
Npad = length(padY);

for p = 0:(Nr-1);
  % Figure aligned X
  subplot(312)
  plot([0:(Nx-1)]-Nx+p+1,X)
  ax = axis;
  axis([xmin,xmax, ax(3), ax(4)]);
  grid on;
  title('X[n-l]')
  % Calculate correlation
  % Pad an X to the appropriate place
  padX = [zeros(1,p),X,zeros(1,Npad-Nx-p)];
  R(p+1) = sum(padX.*padY);
  % Update output display
  subplot(313)
  plot([0:(Nr-1)]-(Nx-1), R);
  axis(axr);
  grid on;
  title('Rxy[l]');
  pause;
end

