www.gusucode.com > Matlab动力系统和时间序列分析工具箱 > Matlab动力系统和时间序列分析工具箱/lab432/toolbox/autocorr_fun.m

    function y=autocorr_fun(x,maxLag);
% AUTOCORR_FUN(x,maxLag) compute autocorrelation function
% Lags from 0 to maxLag
% if output argument not specified acf plotted
%
% last modified 07.12.04


if nargin<2
    prompt = {'Enter maximal lag (in samples)'};
	dlg_title = 'Enter maximal lag';
	num_lines= 1;
	def     = {num2str(min([128 floor(length(x)/2)]))};
	answer  = inputdlg(prompt,dlg_title,num_lines,def);
	if isempty(answer)
        return
    end
    maxLag=str2num(answer{1});
end
      
if ~nargout
    titles='';
        [T,B]=acf(x,maxLag);
        plot(T,B),grid on
        xlim([T(1) T(end)]);
        xlabel('lag (samples)');
else
        [T,y]=acf(x,maxLag);
end

function [T,B]=acf(x,M);
av=mean(x);
T=0:M; 
B=zeros(length(T),1);
for tau=T
    m=length(x)-tau;
    B(tau+1)=mean((x(1:m)-av).*(x(1+tau:m+tau)-av))/var(x(1:m));
end