Validating cross corrolation between sine and cos, shouldn't pahse lag be pi/2? I am trying to use cross correlation instead of FFT to find lags between 2 signals. I am trying to understand cross correlation by using it on sin and cos and expecting phase lag to be pi/2 but it is not:

clc
clear

frequency =1000;
t= linspace(-1000,0.1,1000);


sine_wave = sin(2*pi*frequency*t);
cos_wave  = cos(2*pi*frequency*t);

[xc,lags] = xcorr(cos_wave,sine_wave);
[~,I] = max(abs(xc));

figure
stem(lags,xc,'filled')
legend(sprintf('Maximum at lag %d',lags(I)))
title('Sample Cross-Correlation Sequence')


I am getting a maximum at lag 22 (if you copy and paste the code provided you ll see it in the plot) and I understand that phase lag = 2*pif (time delay) so in my case:

phase lag = 2*pi*1000*22 which is by no means close to pi/2...
What am I missing here?
Thank you
To start with there is a local maxima at 2 lags. If you zoom the x-axis (say axis[-200 200 -500 500]) you can see it more clearly. However, it is not the global maxima and the one at lag 22 is higher.

This is due to the digitization of your sample. If you plot one of your waves against t and zoom the x-axis to say a 200 width box you will see that the peaks clearly have different heights. You therefore get a ringing effect in the resulting cross-correlation.

You could reduce this effect by significantly increasing your sampling rate or decreasing the signal frequency. You currently have ~5 points per $\pi$ of phase which is very low.

You could also adjust your sampling rate/frequency such that an integer number of samples fit exactly in $2\pi$ of phase.