time lag where the phase of the signals is not consistent

4 views (last 30 days)
I have two time series where I have used xcorr to calculate the lag between two signals. However, I am sure that the time lag will not be consistently over the course of the time series. Is there a way to do a moving window time lag or another way to compute how this lag varies through time?
t = TO(:,1);
O1 = TO(:,2);
S1 = TO(:,3);
r = corr(O1,S1)
dt = mean(diff(t));
O1 = O1 - mean(O1);
S1 = S1 - mean(S1);
[c, lags] = xcorr(S1, O1);
lags = lags*dt;
[~, id]= max(abs(c))
ans = lags(id)
figure(1)
plot(lags,c)

Accepted Answer

Mathieu NOE
Mathieu NOE on 3 Feb 2025
Edited: Walter Roberson on 3 Feb 2025
maybe this ?
Split the data in smaller chuncks and do the xcorr on it. you can choose the buffer size and overlap (as you would do in a fft)
load('testfiles.mat')
t = TO(:,1);
O1 = TO(:,2);
S1 = TO(:,3);
dt = mean(diff(t));
O1 = O1 - mean(O1);
S1 = S1 - mean(S1);
% do the xcorr on buffered data to get a delay trend vs time
buffer = 8; % in samples
Overlap = 0.75; % recommended values : between 0.5 and 0.95
dt = mean(diff(t));
[ts,lag_samples] = myxcorr(S1, O1, buffer, Overlap);
time = t(1) + ts*dt; % convert from samples to time and use t(1) as starting point
figure(1)
subplot(2,1,1),plot(t,S1,t,O1)
xlim([min(t) max(t)]);
subplot(2,1,2),plot(time,lag_samples)
xlim([min(t) max(t)]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [time,lag_samples] = myxcorr(x,y, buffer, Overlap)
% compute running xcorr with overlap
samples = length(x);
offset = ceil((1-Overlap)*buffer);
segments = 1+ fix((samples-buffer)/offset); % Number of windows
for ci=1:segments
start = 1+(ci-1)*offset;
stop = start+buffer-1;
[c_a, lag_a] = xcorr(x(start:stop),y(start:stop));
[~, i_a] = max(c_a);
lag_samples(ci) = lag_a(i_a); % lag in samples
end
% time vector (in samples)
% time stamps are defined in the middle of the buffer
time = ((0:segments-1)*offset + round(buffer/2));
end

More Answers (0)

Community Treasure Hunt

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

Start Hunting!