![](/img/trans.png)
[英]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.