xcorr (for autocorrelation) with NaN values

瘦欲@ 提交于 2019-12-11 05:46:15

问题


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');

回答1:


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.




回答2:


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




回答3:


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');


来源:https://stackoverflow.com/questions/7036628/xcorr-for-autocorrelation-with-nan-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!