简体   繁体   English

python为数组创建卷积函数

[英]python creating convolve function for arrays

I have two arrays,我有两个数组,

a = [3, 6, 8, 2, 5, 5]
b = [2, 7, 9]

and I need to create a new array c which takes the values and adds them like this: a[0+0]*b[0] + a[0+1]*b[1] + a[0+2]*b[2] = (3*2) + (6*7) + (9*8) = 6 + 42 + 72 which means c[0] = 120我需要创建一个新的数组c ,它接受这些值并像这样添加它们: a[0+0]*b[0] + a[0+1]*b[1] + a[0+2]*b[2] = (3*2) + (6*7) + (9*8) = 6 + 42 + 72这意味着c[0] = 120

I'm completely lost on how to do this anything to point me in the right direction would be awesome.我完全不知道如何做到这一点,任何为我指明正确方向的事情都会很棒。

total = 0
for n in range(0, min(len(a), len(b))):
    total += a[n] * b[n]

range function范围函数

If c[k] = a[k+0]*b[0] + a[k+1]*b[1] + a[k+2]*b[2]如果c[k] = a[k+0]*b[0] + a[k+1]*b[1] + a[k+2]*b[2]

then然后

>>> c = [sum(i*j for i,j in zip(a[k:], b)) for k in range(4)]
>>> c
[120, 86, 75, 84]

I think this will do what you want.我认为这会做你想做的。 It borrows some of the code from @DukeSilver's answer and makes it build a list, rather than just calculating a single value.它从@DukeSilver 的答案中借用了一些代码,并使其构建了一个列表,而不仅仅是计算单个值。 My assumption is that a is always longer than b .我的假设是a总是比b

c = [sum(a[i+j]*b[j] for j in range(len(b))) for i in range(len(a) - len(b) + 1)]

numpy.convolve还是您想编写自己的函数?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM