Create a gist now

Instantly share code, notes, and snippets.

@shane5ul /autocorr.m
Last active Dec 20, 2015

What would you like to do?
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