Last active
December 20, 2015 12:00
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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