[英]Is there a way to select a subset of a Numpy 2D array using the Manhattan distance?
[英]How to generate a numpy Manhattan distance array with torus geometry fast?
我有一个 N x M 字段,我想创建一个矩阵,其中包含曼哈顿到特定位置的距离。 此外,该场环绕在所有末端(环面)。
我可以在 Numpy 中快速生成这个(不进行缓慢的洪水填充循环)吗?
例如 function 将返回
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]])
这里 position (2,3) 的距离为零,所有其他位置的曼哈顿/出租车距离到 (2,3),同时能够在边缘环绕。
您可以使用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)
可能会有更快的速度,但这应该有效:
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)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.