I want a circular convolution function where I can set the number N
as I like.
N = 7 with zero padding
CodePudding user response:
I think that this should work:
def conv(x1, x2, N): n, m = np.ogrid[:N, :N] return (x1[:N] * x2[(n - m) % N]).sum(axis=1)
This is a direct translation of the formula posted in the question:
To implement this formula, first we compute an array of indices used by x₂. This is done using the code
n, m = np.ogrid[:N, :N] indices = (n - m) % N
For example, for
N=5
, the arrayindices
is:[[0 4 3 2 1] [1 0 4 3 2] [2 1 0 4 3] [3 2 1 0 4] [4 3 2 1 0]]
The entry in the i-th row and j-th column is
(i-j) % N
. Then,x2[indices]
creates an array consisting of elements ofx2
corresponding to these indices. It remains to multiply each row of this array by the firstN
elements ofx1
and take the sum of each row:(x1[:N] * x2[indices]).sum(axis=1)