MATLAB's crosscorr function and R Studio ccf show different results

6 views (last 30 days)
Hi, I'm using MATLAB's crosscorr function and R Studio's ccf. For the same data, the results differ. It appears that the lag axis is flipped in one of them.
I've reproduced the crosscorr documentation example in both and this is what I see. The data is in the attached .txt file.
vs R Studio
Why is this happening? Thanks.
  2 Comments
Bjorn Gustavsson
Bjorn Gustavsson on 14 Dec 2020
They "simply" seems to be flipped. That most likely is because they define the lags in opposite direction. If that's the case you should find the information somewhere in the documentation.
Lizzy Cedeno
Lizzy Cedeno on 14 Dec 2020
Hi, I've checked the documentation for both but couldn't find any information there that implies the lag is treated differently. Thanks for your reply!

Sign in to comment.

Answers (1)

Bjorn Gustavsson
Bjorn Gustavsson on 15 Dec 2020
If you cannot find the information in the documentation, you'll have to go to the source. This is what I find in the xcorr function:
X = fft(x,m2,1);
Y = fft(y,m2,1);
if isreal(x) && isreal(y)
c1 = ifft(X.*conj(Y),[],1,'symmetric');
else
c1 = ifft(X.*conj(Y),[],1);
end
% Keep only the lags we want and move negative lags before positive
% lags.
c = [c1(m2 - mxl + (1:mxl)); c1(1:mxl+1)];
How that differs from the R-implementation I cannot tell. (But without any thinking) This looks like an fft-based convolution between x and y. Exactly which way around to go here requires attention to detail, but you can compare this with the R-version, and check which is what with the wikipedia-description: Cross-correlation.
HTH
  1 Comment
Lizzy Cedeno
Lizzy Cedeno on 19 Dec 2020
Thank you! Yes, from what I've gathered in the past couple of days is that both implementations differ in the order of the arguments: R Studio's ccf(t+k, t) vs MATLAB crosscorr(t, t+k).

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!