Compute autocorrelation function

[block_ac] = block_acf(resids, blocks, make_plot, max_lag) %Matlab & Octave
block_acf <- block_acf(resids, blocks, max_lag, make_plot = TRUE, ...) #R

This function allows calculation of an ACF for a dataset with multiple independent units (for example, data from several individuals, data from multiple dives by an individual animal, etc.). The groups (individual, dive, etc.) should be coded in a categorical variable. The function calculates correlation coefficients over all levels of the categorical variable, but respecting divisions between levels (for example, individual animals are kept separate).

Input var Description Units Default value
resids The variable for which the ACF is to be computed (often a vector of residuals from a fitted model)N/AN/A
blocks A categorical variable indicating the groupings (must be the same length as resids. ACF will be computed only for data points within the same block.)N/AN/A
max_lag ACF will be computed at 0-max_lag lags, ignoring all observations that span blocks. Defaults to the minimum number of observations in any block. The function will allow you to specify a max_lag longer than the shortest block if you so choose.N/AN/A
make_plot Logical. Should a plot be produced? Defaults to TRUE.LogicalTRUE(#R) or 1(%Mat. and Oct.)
Output var Description Units
block_acf The calculated correlation coefficients over all levels of the categorical variable along with a plot of the coefficients if make_plot = TRUE N/A

Matlab & Octave

resids = randn(150,1)
% in real life resids are normally residuals from a
% fitted model, not random numbers
blocks = [repmat('animal1', 25, 1); repmat('animal2', 70, 1); ...
repmat('animal3', (150-25-70), 1)] ;
block_ac = block_acf(resids, blocks, 1, 10) ; %plot 1st 10 lags

R

block_acf(resids=ChickWeight$weight, blocks=ChickWeight$Chick)