Numpy Convolution implementation for mode = same

Viewed 373

I hope I chose the right platform for this question (wonders if it’s more related to math exchange or computer science).

In any regard, I’ve read about convolution in signal processing and I want to try to implement it. I was able to calculate convolution to the length of N+M-1.

This can be done with the following function (Python):

def convolve(x, h):
    xLen = len(x)
    hLen = len(h)
    if xLen == 0 or hLen == 0:
        return None

    totalLength = xLen + hLen - 1
    init = 0

    y = [0] * totalLength
    for n in range(init, totalLength):
        yn = 0
        k = max(0, n + 1 - xLen)
        j = n - k
        while k < hLen and j >= 0:
            yn += x[j] * h[k]
            j -= 1
            k += 1
        y[n] = yn
    return y

This is the the same as using numpy.convolve with mode=full.

My issue is that I don’t understand numpys mode=same, which performs the convolution till MAX(n, m). How can I calculate the convolution until that length without distorting the signal ?

In other words, I’d love to know how numpy implemented mode=same.

Thanks a lot!

1 Answers
Related