function r = acf(data,lag)

% ACF   Autocorrelation function.
%
%  R = ACF(DATA) -- Autocorr. coef. of vector DATA at lag 1.
%  R = ACF(DATA,LAG) -- Autocorr. coefficients at various lags.
%
%  Example:  acf(log([1:100]'),1:3) == [0.9983 0.9957 0.9929]
%
%  See also PACF,CORRCOEF.

% Original coding by Alexander Petrov, Ohio State University.
% $Revision: 1.0 $  $Date: 1999/12/19 00:20 $
%
% Part of the utils toolbox version 1.1 for MATLAB version 5 and up.
% http://alexpetrov.com/softw/utils/
% Copyright (c) Alexander Petrov 1999-2006, http://alexpetrov.com
% Please read the LICENSE and NO WARRANTY statement in ../utils_license.m

if (nargin==1)
  lag = 1 ;    % default
end

d = data(:) ;  % reshape into a column vector
N = length(data) ;
n = length(lag) ;
r = zeros(size(lag)) ;

for k = 1:n
  L = lag(k) ;
  if (L>N | L<0)
    r(k) = NaN ;
  else
    x = [d(1:end-L) d(1+L:end)] ;
    corr = corrcoef(x) ;
    r(k) = corr(1,2) ;
  end
end

%%  Return R
%%%%% End of ACF.M
