Take the 2-minute tour ×

I'd like to autocorrelate some data but it has some missing values, is there a quick way to do this in matlab? xcorr returns an array of NaN if any of the input is NaN.


data = [1 2 3 4 NaN 2 3 4 1 2 3 4];
xc = xcorr(data, 'biased');
share|improve this question
add comment

3 Answers

up vote 2 down vote accepted

With some insight from Nzbuu, the following works:

data = [1 2 3 4 NaN 2 3 4 5];

scaled = (data - nanmean(data)) / nanstd(data);
scaled(isnan(data)) = 0;

corr = xcorr(scaled);

It is necessary to insert zeros after scaling the data, not before, as otherwise this will affect the value of mu and std used within xcorr. It is better to do this, than simply working out xcorr directly, as the fft approach used within xcorr is much faster for big datasets.

share|improve this answer
add comment

Sure. You can use indexing to select only those items that aren't NaN and call xcorr on that.

xc = xcorr(data(~isnan(data)), 'biased');
share|improve this answer
surely that lets 4 and 2 involve themselves at lag=1 when that pairing should be included in lag=2? –  Alex Aug 12 '11 at 10:33
It's either that or replacing the NaN values with zero: data(isnan(data)) = 0; –  Nzbuu Aug 12 '11 at 12:59
add comment

I would prefer excluding from the correlation the couples with NaN's instead of introducing zeros. In this case I would use the following code in matlab, based on corr (Pearson's autocorrelation coefficients).

for i=2:nlags+1
title('sample ACF')

Hope it Helps

share|improve this answer
if you add zeros you are going to bias the result and if you take off the NaNs you are going to compromise the lags relation. IMHO the proper way to do it is to take off the couples including NaNs after having applied the back-shift operator (as I showed above) –  Fabio Apr 30 '13 at 9:14
add comment

Your Answer


