gpt4 book ai didi

python - 因互相关而滞后?

转载 作者:太空狗 更新时间:2023-10-29 22:25:17 27 4
gpt4 key购买 nike

假设有两个信号:

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)

我想移动第一个信号以匹配第二个信号。我知道这可以使用互相关来完成,正如 Matlab 所证明的那样,但我如何使用 SciPy 来完成它。

最佳答案

先看一些例子。假设我们已经在单元测试课上了。

# Autocorrelation.
y1 = [1, 1, 0, 0, 1, -1, -1]
corr, lag = cross_corr(y1, y1)
self.assertEqual(lag, 0)

y1 = [1, 1, 0 ,1, -1, -1]
y2 = [1, 0, 1, 0, 0, 2]
corr, lag = cross_corr(y1, y2)
self.assertEqual(lag, -2)

这是我的代码。

import numpy as np    

def cross_corr(y1, y2):
"""Calculates the cross correlation and lags without normalization.

The definition of the discrete cross-correlation is in:
https://www.mathworks.com/help/matlab/ref/xcorr.html

Args:
y1, y2: Should have the same length.

Returns:
max_corr: Maximum correlation without normalization.
lag: The lag in terms of the index.
"""
if len(y1) != len(y2):
raise ValueError('The lengths of the inputs should be the same.')

y1_auto_corr = np.dot(y1, y1) / len(y1)
y2_auto_corr = np.dot(y2, y2) / len(y1)
corr = np.correlate(y1, y2, mode='same')
# The unbiased sample size is N - lag.
unbiased_sample_size = np.correlate(
np.ones(len(y1)), np.ones(len(y1)), mode='same')
corr = corr / unbiased_sample_size / np.sqrt(y1_auto_corr * y2_auto_corr)
shift = len(y1) // 2

max_corr = np.max(corr)
argmax_corr = np.argmax(corr)
return max_corr, argmax_corr - shift

关于python - 因互相关而滞后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39336727/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com