%%% This code is for illustrating the normalized autocorrelation 
%%% Rx[n] of a %%% finite-length signal x[n] that is non-zero
%%% for 0 <= n <= N-1.
%%%
%%% Please use the MATLAB command xcorr(x) for autocorrelation
%%% and xcorr(x)/length(x) for normalized autocorrelation.
%%%
%%% Programmer:   Prof. Brian L. Evans
%%% Organization: The University of Texas at Austin
%%% Date:         March 26, 2018
%%%
%%% Normalized autocorrelation for real-valued x[n] is
%%%
%%          1    N-1          
%%% Rx[n] = -    Sum     x[k] x[n+k]
%%%         N   k=-(N-1)
%%%
%%% Note that Rx[n] = x[n] * x[-n] where * is convolution.
%%%
%%% Since x[n] has N samples, Rx[n] will have 2N-1 samples
%%% centered at the origin.
%%%
%%% To simplify the limits of summation, notice that
%%%
%%%   x[k] is not zero for 0 <= k <= N-1
%%%   x[n+k] is not zero of 0 <= n+k <= N-1 or -n <= k <= N-1-n
%%%
%%% In MATLAB, Rx will be a vector of 2N-1 elements.  Index 
%%% n = -(N-1) will correspond to the first element of vector Rx.
%%%
length31 = ones(1, 31);     % replace with PN sequence
x = [length31 length31];    % x holds two periods
N = length(x);
Rx = zeros(1, 2*N-1);       % Rx[n] has 2N-1 samples
Roffset = N;                % Maps n = -(N-1) to index 1 for Rx[n]
xoffset = 1;                % Maps k = 0 to index 1 for x[k]
for n = -(N-1) : (N-1)
   kmin = max(0, -n);
   kmax = min(N-1, N-1-n);
   for k = kmin : kmax
      Rx(n + Roffset) = Rx(n + Roffset) + x(k+xoffset) * x(n+k+xoffset);
   end
   Rx(n + Roffset) = (1/N) * Rx(n + Roffset);    % normalize
end
