I have point_coords
ndarray:
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()
It looks like:
point_coords
array([[ 62, -31],
[ 49, 33],
[ -2, -86],
[ -29, 49],
...
I want to get a square matrix with distance between points. How am I supposed to do it?
CodePudding user response:
>>> 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. ]])
If only numpy is to be used:
np.linalg.norm(point_coords[:, None, :] - point_coords[None, :, :], axis=-1)
CodePudding user response:
You can do it using solely Numpy:
Compute deltas by each coordinate (square matrices):
dx = point_coord_x[:, np.newaxis] - point_coord_x[np.newaxis, :]
dy = point_coord_y[:, np.newaxis] - point_coord_y[np.newaxis, :]
Then compute the distance array from these deltas:
result = np.sqrt(dx ** 2 dy ** 2)