I am trying to compute the cross correlation (CC) between two signals (x & y) in Matlab. I started with a simple sine code. To make sure I was computing correctly I incorporated a phase shift in the y signal. I wrote a code to determine the phase shift, circshift the y signal and then compute the correlation. I used two methods for computing the CC: (1) xcorr (2) Fourier transform. Here is the code:
% Define the two signals
DeltaT = 0.01;
t = 0:DeltaT:2*pi-DeltaT;
x = sin(t);
y = sin(t+pi/2);
% Compute the Fourier transforms of the two signals
X = fft(x);
Y = fft(y);
[maxValue, pos] = max(abs(X));
phaseDiff = angle(Y(pos)) - angle(X(pos));
% Perform a phase shift on signal y
shiftAmount = round(phaseDiff / (DeltaT));
y_shifted = circshift(y,shiftAmount);
YSHIFTED = fft(y_shifted);
% Compute the cross-power spectrum
R = X .* conj(YSHIFTED) ./ abs(X .* conj(YSHIFTED));
% Compute the inverse Fourier transform of the cross-power spectrum
r = ifft(R);
% Find the index of the maximum correlation
[max_corr, idx] = max(abs(r));
% Display the results
fprintf('Correlation: %f\n', max_corr);
fprintf('Phase difference: %f\n', phaseDiff);
% Plot the results
plot(t,x,LW,1.5);
hold on
plot(t,y_shifted,'--',LW,1.5);
plot(t,y,LW,1.5);
legend('x','yshifted','y')
grid on
xticks([0, pi/2, pi, 3*pi/2, 2*pi])
% Method II
disp('Method II')
% Compute the auto-correlations of the two signals
auto_x = xcorr(x, 'coeff');
auto_y = xcorr(y_shifted, 'coeff');
% Compute the normalized cross-correlation between the two signals
[c, lags] = xcorr(x, y_shifted, 'coeff');
% Plot the normalized cross-correlation
figure;
plot(lags, c);
xlabel('Lag');
ylabel('Normalized Cross-correlation');
title('Normalized Cross-correlation between x and y');
% Find the maximum correlation and the corresponding lag
[max_corr, max_lag_idx] = max(c);
max_lag = lags(max_lag_idx);
% Display the results
fprintf('Maximum correlation: %f\n', max_corr);
I am particularly confused at the results when the phase shift is pi/2. From the plotted figures it is obvious that the code is able to detect the phase shift and realign the signal. The x and y_shifted are now overlapping. So the CC should be 1. But I get value which is 0.7, which makes no sense. Also the values differ slightly when the t is taken t = 0:DeltaT:2*pi-DeltaT; or t = 0:DeltaT:2*pi+DeltaT; Can someone explain what is going on here computationally?