Skip to content

Instantly share code, notes, and snippets.

@shane5ul
Last active December 20, 2015 12:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shane5ul/6128047 to your computer and use it in GitHub Desktop.
Save shane5ul/6128047 to your computer and use it in GitHub Desktop.
Given a vector "x", computes the autocorrelation function A = <x(t) x(0)>/<x(0) x(0)>. If a second argument NA is specified, only the first NA elements of "A" are computed; otherwise, NA = N - 1 by default.
function A = autocorr(x, NA)
%
% Given a vector "x", computes the autocorrelation function A = <x(t) x(0)>/<x(0) x(0)>
%
% If a second argument NA is specified, only the first NA elements of "A" are computed
% Otherwise, NA = N - 1 by default.
%
x = x - mean(x); % subtract mean from "x"
N = length(x); % size of "x"
%
% If NA is not specified
%
if(nargin < 2)
NA = N - 1;
end
A = zeros(NA,1);
%
% Calculation below is written for clarity
% and not for speed
%
for i = 1:NA
x1 = x(1:N-i+1); % both terms have N - i + 1 terms
x2 = x(i:N);
A(i) = mean(x1 .* x2);
end
A = A/A(1);
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment