检查给定系统的脉冲响应



我写了一个代码,它以一个矢量作为输入(脉冲(,并应该返回另一个矢量(脉冲响应(。

import numpy as np
from scipy import signal

y = signal.unit_impulse(8)
def response(y):
for i in range(8):
g = np.zeros(len(y))
g[i] = 3 * y[i] -2 * y[i - 1] + 2 * y[i -2]
return g
print(g)

signal.unit_impulse(8)创建一个具有8位数字的矢量,其中第一位为1,其余为零。当我运行这个程序时,我会得到NameError: name 'g' is not defined.。在函数逻辑中,我会收到一个通知Local variable 'g' might be referenced before assignment。我认为这两种说法有某种关联。我该怎么解决这个问题?

您只需要缩进g,因为函数当前没有返回它。

def response(y):
g = np.zeros(len(y))
for i in range(8):
g[i] = 3 * y[i] -2 * y[i - 1] + 2 * y[i -2]
return g

我已经通过以下方式修复了此代码:

  • 确保压痕一致且合理
  • for循环之前,在response函数中定义g(否则,您将在循环的每次迭代过程中重新初始化g(
  • 函数定义结束后,将g定义为以y为输入调用response函数时的输出(如果g仅在函数范围内定义,则函数范围外的代码将无法访问它(
import numpy as np
from scipy import signal

y = signal.unit_impulse(8)
def response(y):
g = np.zeros(len(y))
for i in range(8):
g[i] = 3 * y[i] -2 * y[i - 1] + 2 * y[i -2]
return g
g = response(y)
print(g)

此代码提供以下输出:

[ 3. -2.  2.  0.  0.  0.  0.  0.]

最新更新