A few things that will make this faster:
First, with your array of points, instead of nested arrays of length 1 ndarrays, you can just make an Nx2
ndarray:
points = np.random.random((N, 2))
Next, you end up computing each pairwise distance many times, you should compute each distance once and then loop over the elements of the array. Scipy can do this calculation for you using scipy.spatial.distance.pdist
. To recover a pairwise distance matrix, you must use scipy.spatial.distance.squareform
. Explicitly looping over the elements of the matrix:
r1 = []
r2 = []
d = squareform(pdist(points))
for i in range(N):
for j in range(N):
for k in range(N):
r1.append(d[i,j])
r2.append(d[i,k])
Finally, you can make it simpler still by noting the relationship between the pairwise distance matrix d
and the outputs r1
and r2
(which you can do by inspection for some small N
, like 3). Using some array manipulation, you can recover the same arrays using:
d = squareform(pdist(points))
r1 = np.tile(d.reshape((N**2, 1)), N).flatten()
r2 = np.tile(d, N).flatten()
Using only a moderate N=20
, on my slow computer, while your code runs in 1.15 s, the method of explicitly looping takes 12.7 ms, and the array manipulation shortcut takes 362 µs, and the latter two should scale better than the original code.