I have two signals, both recorded at the same sampling frequency, however one has a phase delay. I am currently playing around trying to figure out how to calculate the time delay between these two signals using the cross correlation method. I want to calculate the time delay between these two signals using windows, as I want the dynamic time delay of the signals and not the time delay over the entire spectrum. How do I do this? I am using matlab and for now I have this code, but I am unsure whether or not I am doing the right thing. How would I be able to get the maximum peaks of the correlation of all the columns in my "corr" matrix, and how do I convert this into a time delay?
file_path1 = '\ref trigger new_000_ALL.csv';
file_path2 = '\meas trigger new_000_ALL.csv';
% Read the CSV file skipping the first 17 rows
ref = csvread(file_path1, 16, 0);
meas = csvread(file_path2, 16, 0);
signal_ref = ref(:,2);
signal_meas = meas(:,2);
n = length(signal_ref);
dt = 3.2e-6;
fs = 1/dt;
FFT_ref = fft(signal_ref);
FFT_ref = FFT_ref(1:n/2);
FFT_meas = fft(signal_meas);
FFT_meas = FFT_meas(1:n/2);
FFT_n = length(FFT_meas);
window_size = 46; % Amount of data point used to separate data chunks.
overlap_percentage = 50; % Desired overlap percentage
overlap = window_size * overlap_percentage / 100;
shift = window_size-overlap; % nb of samples between 2 contiguous buffers
% Calculate number of windows
num_windows = fix((FFT_n-window_size)/shift +1);
corr_values = cell(num_windows, 1);
lags_values = cell(num_windows, 1);
% Iterate over the signal with sliding window
for ci = 1:num_windows
% Define start and end indices for the current window
start_index = 1+(ci-1)*shift;
end_index = min(start_index+ window_size-1,FFT_n);
% Extract the current window
window_ref = FFT_ref(start_index:end_index);
window_meas = FFT_meas(start_index:end_index);
ifft_ref = ifft(window_ref);
ifft_meas = ifft(window_meas);
[corr_temp, lags_temp] = xcorr(ifft_ref, ifft_meas);
corr_values{ci} = corr_temp;
lags_values{ci} = lags_temp;
end
% Concatenate all correlation and lags values
corr = cell2mat(corr_values');
lags = cell2mat(lags_values);
lag = lags(1,:);
figure(1)
plot(Time, signal_ref);
xlabel('Time (s)');
ylabel('Voltage (V)');
title('Reference signal')
figure(2)
plot(Time, signal_meas)
xlabel('Time (s)')
ylabel('Voltage (V)')
title('Measured signal')
figure(3)
plot(Freq, real(FFT_ref));
xlabel('Frequency (Hz)');
ylabel('Magnitude');
title('Reference signal')
figure(4)
plot(Freq, real(FFT_meas))
xlabel('Frequency (Hz)')
ylabel('Magnitude')
title('Measured signal')
figure(5)
plot(lag, abs(corr(:,20)));
xlabel('Cross correlation shift (GHz)')
ylabel('Amplitude (A.U.')




