Ray
Ray

Reputation: 15

How to np.convolve over two 2d arrays

I want to carry out np.convolve for two 2d arrays in a vectorized manner. Here is the thing:

The function np.convolve takes two 1d arrays, a and v, and computes the convolution. The result reads:

output[n] = \sum_m a[m] v[n - m] .

What I want to do is, for 2d arrays a and v, to repeat "convolution along axis=0" over axis=1. That is,

output[n][k] = \sum_m a[m][k] v[n - m][k] .

Though this is attained by a for statement with respect to the axis=1, I'm keen on finding a way to "vectorize" this to improve performance.

I looked up for a while but no clue. I'm glad if someone could find a way out. Thank you so much.

Upvotes: 0

Views: 1106

Answers (1)

jhso
jhso

Reputation: 3283

Depending on the size of your arrays it may be quicker to do a multiplication of the fft arrays, which is mathematically equivalent to the convolution operation. Based on the answer here, it is quicker, however it appears limited when you get to exceptionally long sequences, as proven here. An example of what this could look like:

from scipy.signal import fftconvolve
output = fftconvolve(a, v, mode='same') #mode='full', too

If they help you don't forget to give them an upvote, too :).

Upvotes: 1

Related Questions