Get lag with cross-correlation?

2019-02-07 09:09发布

问题:

Let's say have have two signals:

import numpy
dt = 0.001

t_steps = np.arange(0, 1, dt)
a_sig = np.sin(2*np.pi*t_steps*4+5)
b_sig = np.sin(2*np.pi*t_steps*4)

I want to shift the first signal to match the second signal. I know this can be completed using cross-correlation, as evidenced by Matlab, but how do I accomplish this with SciPy.

回答1:

As defined in this Wikipedia article, the lag between signals is given by the argmax of the cross-correlation. Consequently, the following code will shift the b_sig to be in phased with a_sig to minimize the error.

from scipy.signal import correlate

lag = np.argmax(correlate(a_sig, b_sig))
c_sig = np.roll(b_sig, shift=int(np.ceil(lag)))