xcorr (for autocorrelation) with NaN values
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.
e.g.
data = [1 2 3 4 NaN 2 3 4 1 2 3开发者_如何学运维 4];
xc = xcorr(data, 'biased');
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.
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).
out=zeros(nlags,1);
out(1)=1;
for i=2:nlags+1
out(i)=corr(data(i:end),data(1:end-i+1),'rows','complete');
end
stem(0:nlags,out)
title('sample ACF')
Hope it Helps
Sure. You can use indexing to select only those items that aren't NaN and call xcorr
on that.
data = [1 2 3 4 NaN 2 3 4 1 2 3 4];
xc = xcorr(data(~isnan(data)), 'biased');
精彩评论