The following function computes the correlation between two vectors.
It doesn't give the same result as matlab function for small values:
I am really don't know if the bug becomes from this function or not ? the maximum lags by default is N-1 ? is this reasonable ?
inline int pow2i(int x) { return ((x < 0) ? 0 : (1 << x)); }`
vec xcorr(vec x, vec y,bool autoflag)
{
int maxlag=0;
int N = std::max(x.size(), y.size());
//Compute the FFT size as the "next power of 2" of the input vector's length (max)
int b = ceil(log2(2.0 * N - 1));
int fftsize = pow2i(b);
int e = fftsize - 1;
cx_vec temp2;
if (autoflag == true) {
//Take FFT of input vector
cx_vec X = cx_vec(x,zeros(x.size()));
X= fft(X,fftsize);
//Compute the abs(X).^2 and take the inverse FFT.
temp2 = ifft(X%conj(X));
}
else{
//Take FFT of input vectors
cx_vec X=cx_vec(x,zeros(x.size()));
cx_vec Y=cx_vec(y,zeros(y.size()));
X = fft(X,fftsize);
Y = fft(Y,fftsize);
//cout<< "Y " << Y << endl;
//cout<< "X " << X<< endl;
temp2 =ifft(X%conj(Y));
//cout<< "temp 2 " << temp2 << endl;
}
maxlag=N-1;
vec out=real(join_cols(temp2(span(e - maxlag + 1, e)),temp2(span(0,maxlag))));
return out;
}