Python问题(卷积)
如何在不使用预定义方法的情况下为for循环编写三行代码 我试过:Python问题(卷积),python,numpy,Python,Numpy,如何在不使用预定义方法的情况下为for循环编写三行代码 我试过: h = np.array([1, 1, 1, 0, 0]) x = np.array([0.5, 2, 0, 0, 0]) length = len(h)+len(x)-1 h_conv, h_rev, x_conv, y_conv = np.zeros(length), np.zeros(length), np.zeros(length), np.zeros(length) x_conv[:len(x)] = x h_rev
h = np.array([1, 1, 1, 0, 0])
x = np.array([0.5, 2, 0, 0, 0])
length = len(h)+len(x)-1
h_conv, h_rev, x_conv, y_conv = np.zeros(length), np.zeros(length), np.zeros(length), np.zeros(length)
x_conv[:len(x)] = x
h_rev[length-len(h):] = h[::-1].copy()
for t in range(length):
h_conv[:t+1] = h_rev[length-t-1:]
y_conv[t] = np.sum(x_conv * h_conv)
>>> y
[0.5, 2.5, 2.5, 2., 0., 0., 0., 0., 0.]
代码的问题是
j
可能大于i
。你是说:
for i in range(length):
y[i]=0;
for j in range(length):
y[i] += x[i-j]*h[j];
Error index 0 is out of bounds for axis with size 0
或者可能是i+1
for i in range(length):
y[i]=0;
for j in range(i):
y[i] += x[i-j]*h[j];