Vectorizing sum of nearest neighbours in matrix using Numpy

Viewed 955

Given a matrix an N by N matrix A I want to construct another N by N matrix B such that its entries are given by:

B_{i,j} = A_{i+1, j} + A_{i-1, j} + A_{i, j+1} + A_{i, j-1}

Note that the system uses periodic boundary conditions so

A_{N, j} = A_{0, j}

A_{i, -1} = A{i, N-1}

And so on.

How can I do this as a vectorized operation in numpy?

1 Answers
Related