我有point_coordsndarray:
point_coord_x = np.array([np.random.randint(low=-100, high=100) for i in range(40)])
point_coord_y = np.array([np.random.randint(low=-100, high=100) for i in range(40)])
point_coords = np.array([point_coord_x, point_coord_y]).transpose()
看起來像:
point_coords
array([[ 62, -31],
[ 49, 33],
[ -2, -86],
[ -29, 49],
...
我想得到一個點之間距離的方陣。我該怎么做?
uj5u.com熱心網友回復:
>>> from scipy.spatial import distance_matrix
>>> distance_matrix(point_coords, point_coords)
array([[ 0. , 149.21461054, 88.64536085, ..., 44.94441011, 24.73863375, 60.5309838 ],
[149.21461054, 0. , 122.64175472, ..., 136.47344064, 163.60012225, 201.07958623],
[ 88.64536085, 122.64175472, 0. , ..., 45.01110974, 113.35784049, 147.2752525 ],
...,
[ 44.94441011, 136.47344064, 45.01110974, ..., 0. , 69.57010852, 102.3132445 ],
[ 24.73863375, 163.60012225, 113.35784049, ..., 69.57010852, 0. , 38.62641583],
[ 60.5309838 , 201.07958623, 147.2752525 , ..., 102.3132445 , 38.62641583, 0. ]])
如果只使用 numpy:
np.linalg.norm(point_coords[:, None, :] - point_coords[None, :, :], axis=-1)
uj5u.com熱心網友回復:
您可以僅使用Numpy來做到這一點:
按每個坐標(方陣)計算增量:
dx = point_coord_x[:, np.newaxis] - point_coord_x[np.newaxis, :]
dy = point_coord_y[:, np.newaxis] - point_coord_y[np.newaxis, :]
然后從這些增量計算距離陣列:
result = np.sqrt(dx ** 2 dy ** 2)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/338390.html
