'What is the best way to implement 1D-Convolution in python?

I am trying to implement 1D-convolution for signals.

It should have the same output as

ary1 = np.array([1, 1, 2, 2, 1])
ary2 = np.array([1, 1, 1, 3])
conv_ary = np.convolve(ary2, ary1, 'full')

>>>> [1 2 4 8 8 9 7 3]

I came up with this approach:

def convolve_1d(signal, kernel):
    n_sig = signal.size
    n_ker = kernel.size
    n_conv = n_sig - n_ker + 1

    # by a factor of 3.
    rev_kernel = kernel[::-1].copy()
    result = np.zeros(n_conv, dtype=np.double)
    for i in range(n_conv):
        result[i] = np.dot(signal[i: i + n_ker], rev_kernel)
    return result

But my result is [8,8] I might have to zero pad my array instead and change its indexing.

Is there a smoother way to achieve the desired outcome?

Thanks in advance!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source