Python 有效地创建numpy阵列,减少远离中心的值

Python 有效地创建numpy阵列,减少远离中心的值,python,numpy,Python,Numpy,设N为奇数正整数。我想创建一个形状为nxn的二维正方形网格,其中中心元素为N,周围的8-邻域的值为N-1,该邻域周围的元素的值为N-2,以此类推,这样最终数组的外壳的值为N//2。我可以在一个for循环中使用np.pad实现这一点,该循环将shell迭代添加到数组中: def pad_decreasing(N): assert N % 2 == 1 a = np.array([[N]]) for n in range(N-1, N//2, -1): a =

设N为奇数正整数。我想创建一个形状为nxn的二维正方形网格,其中中心元素为N,周围的8-邻域的值为N-1,该邻域周围的元素的值为N-2,以此类推,这样最终数组的外壳的值为N//2。我可以在一个for循环中使用np.pad实现这一点,该循环将shell迭代添加到数组中:

def pad_decreasing(N):
    assert N % 2 == 1
    a = np.array([[N]])
    for n in range(N-1, N//2, -1):
        a = np.pad(a, 1, mode='constant', constant_values=n)
    return a
示例输出:

In: pad_decreasing(5)
Out: 
array([[3, 3, 3, 3, 3],
       [3, 4, 4, 4, 3],
       [3, 4, 5, 4, 3],
       [3, 4, 4, 4, 3],
       [3, 3, 3, 3, 3]])

问题。我可以用一种不依赖于for循环的矢量化形式来实现这一点吗。该代码对于N大的点相当慢。

中心与网格中任何点之间的距离可以写成np.maximumnp.absrow-center,np.abscol-center;然后N减去这个距离得到你需要的洋葱:

N = 5

# the x and y coordinate of the center point
center = (N - 1) / 2

# the coordinates of the square array
row, col = np.ogrid[:N, :N]

# N - distance gives the result
N - np.maximum(np.abs(row - center), np.abs(col - center))

# array([[3, 3, 3, 3, 3],
#        [3, 4, 4, 4, 3],
#        [3, 4, 5, 4, 3],
#        [3, 4, 4, 4, 3],
#        [3, 3, 3, 3, 3]])