MATLAB: How to Align Two Signals Better

fillmissingMATLAB

s1 and s2 data attached, however, running the code below, td I got is -24482. 
By plotting s1 and s2, the shifting is not that big. How to improve this function? Thank you very much. 
function [td,ny]=align_signal(s1,s2) 
ny=ones(size(s1))*NaN; 
[C21,lag21] = xcorr(s2,s1); 
C21 = C21/nanmax(C21); 
[M21,I21] = nanmax(C21); 
t21 = lag21(I21); 
if t21<0 
ny(-t21:end) = s1(-t21:end); 
else 
ny(t21:end)=s1(t21:end); 
end 
td=abs(t21);

Best Answer

From looking at your data, it appears that the root cause for the large td value is due to the presence of “NaN” values in the “s2” data vector.  Consider filling in the missing data in this data vector, for example, using the “fillmissing” function, prior to calling the “align_signal” function you provided.
 
I was able to confirm that the “td” value as the output of the “align_signal” function is 4 instead of 24482 when I used linear interpolation to fill the missing data in “s2”.