Open1

任意の基準座標 [x,y] から任意の複数座標 [x,y] x N点 までのそれぞれの距離をNumpyで一括算出したうえで最近傍の点を抽出する

PINTOPINTO
import numpy as np

base_point = np.asarray(
    [10,7],
    dtype=np.float32,
)
points = np.asarray(
    [
        [7,3],
        [5,5],
        [0,6],
        [5,9],
        [7,3],
    ],
    dtype=np.float32,
)
diff_val = points - base_point
print(f'diff_val: {diff_val}')
every_distance = np.linalg.norm(diff_val, axis=1)
print(f'every_distance: {every_distance}')

nearest_point_index = np.argmin(every_distance)
print(f'nearest_distance: {every_distance[nearest_point_index]}')
print(f'nearest_point_index: {nearest_point_index}')
print(f'nearest_point: {points[nearest_point_index]}')
diff_val: [
    [ -3.  -4.]
    [ -5.  -2.]
    [-10.  -1.]
    [ -5.   2.]
]
every_distance: [ 
    5.
    5.3851647
    10.049875
    5.3851647
]

nearest_distance: 5.0
nearest_point_index: 0
nearest_point: [7. 3.]