且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Matlab 中使用 FFT 计算自相关

更新时间:2021-09-24 23:37:01

就像你说的,取 fft 并逐点乘以其复共轭,然后使用逆 fft(或者在两个信号互相关的情况下): Corr(x,y) FFT(x)FFT(y)*)

Just like you stated, take the fft and multiply pointwise by its complex conjugate, then use the inverse fft (or in the case of cross-correlation of two signals: Corr(x,y) <=> FFT(x)FFT(y)*)

x = rand(100,1);
len = length(x);

%# autocorrelation
nfft = 2^nextpow2(2*len-1);
r = ifft( fft(x,nfft) .* conj(fft(x,nfft)) );

%# rearrange and keep values corresponding to lags: -(len-1):+(len-1)
r = [r(end-len+2:end) ; r(1:len)];

%# compare with MATLAB's XCORR output
all( (xcorr(x)-r) < 1e-10 )

事实上,如果你看一下xcorr.m的代码,这正是它在做的(只是它必须处理填充、归一化、向量/矩阵输入等所有情况...)

In fact, if you look at the code of xcorr.m, that's exactly what it's doing (only it has to deal with all the cases of padding, normalizing, vector/matrix input, etc...)