如何快速生成具有圆环几何体的numpy Manhattan距离阵列?

2024-05-31 23:59:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个nxm字段,我想创建一个矩阵,其中包含到特定位置的曼哈顿距离。此外,场在所有端部(圆环体)上环绕

我能以Numpy fast(无需执行缓慢的洪水填充循环)生成此文件吗

例如,函数将返回

f(x=2, y=3, size_x=8, size_y=8) ->

array([[5, 4, 3, 2, 3, 4, 5, 6],
       [4, 3, 2, 1, 2, 3, 4, 5],
       [3, 2, 1, 0, 1, 2, 3, 4],
       [4, 3, 2, 1, 2, 3, 4, 5],
       [5, 4, 3, 2, 3, 4, 5, 6],
       [6, 5, 4, 3, 4, 5, 6, 7],
       [7, 6, 5, 4, 5, 6, 7, 8],
       [6, 5, 4, 3, 4, 5, 6, 7]])

此处位置(2,3)的距离为零,所有其他位置的距离为曼哈顿/出租车的距离(2,3),同时能够在边缘缠绕


Tags: 文件函数numpy距离size矩阵array边缘
2条回答

可能会有更快的方法,但这应该有效:

def f(x=2, y=3, X=8, Y=8):
    return np.array([[min(abs(y-i), abs(Y+y-i))+min(abs(x-j), abs(X+x-j)) for i in range(Y)] for j in range(X)])

您可以使用numpy.roll为x轴和y轴上的移位创建模板,然后使用numpy.add.outer按轴添加它们

import numpy as np

def f(x, y, size_x, size_y):
    """
    >>> f(x=2, y=3, size_x=8, size_y=8)
    array([[5, 4, 3, 2, 3, 4, 5, 6],
           [4, 3, 2, 1, 2, 3, 4, 5],
           [3, 2, 1, 0, 1, 2, 3, 4],
           [4, 3, 2, 1, 2, 3, 4, 5],
           [5, 4, 3, 2, 3, 4, 5, 6],
           [6, 5, 4, 3, 4, 5, 6, 7],
           [7, 6, 5, 4, 5, 6, 7, 8],
           [6, 5, 4, 3, 4, 5, 6, 7]])
    >>> f(x=1, y=1, size_x=3, size_y=3)
    array([[2, 1, 2],
           [1, 0, 1],
           [2, 1, 2]])
    """
    a, b = divmod(size_x, 2)
    x_template = np.r_[:a+b, a:0:-1] # [0 1 2 1] for size_x == 4 and [0 1 2 2 1] for size_x == 5
    x_template = np.roll(x_template, x) # for x == 2, size_x == 8: [2 1 0 1 2 3 4 3]
    a, b = divmod(size_y, 2)
    y_template = np.r_[:a+b, a:0:-1]
    y_template = np.roll(y_template, y)
    return np.add.outer(x_template, y_template)

相关问题 更多 >