使用Numpy在矩阵中矢量化最近邻居的总和

时间:2016-03-10 19:17:47

标签: python numpy convolution

给定矩阵一个N乘N矩阵A我想构造另一个N乘N矩阵B,使得它的条目由下式给出:

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

请注意,系统使用周期性边界条件,所以

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

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

等等。

如何在numpy中执行矢量化操作?

1 个答案:

答案 0 :(得分:1)

您所描述的操作是convolution。您可以使用scipy.ndimage.convolve

import numpy as np
from scipy.ndimage import convolve, generate_binary_structure

gen = np.random.RandomState(0)
A = gen.random_integers(0, 3, (6, 6))   # input array
k = generate_binary_structure(2, 1)     # kernel
B = convolve(A, k, mode='wrap')         # use mode='wrap' for periodic boundaries

print(A)
# [[0 3 1 0 3 3]
#  [3 3 1 3 1 2]
#  [0 3 2 0 0 0]
#  [2 1 2 3 3 2]
#  [0 1 1 1 1 0]
#  [1 0 3 0 3 1]]

print(k)
# [[False  True False]
#  [ True  True  True]
#  [False  True False]]

print(B)
# [[10  7  8  7 10  9]
#  [ 8 13 10  5  9  9]
#  [ 8  9  8  8  4  4]
#  [ 5  9  9  9  9  7]
#  [ 4  3  8  6  8  4]
#  [ 2  8  5  7  8  8]]