Home > Back-end >  Calculating distance between each element of an array
Calculating distance between each element of an array

Time:09-23

I have an array,

a = np.array([1, 3, 5, 10])

I would like to create a function that calculates the distance between each of its elements from every other element. There should be no for loop as speed is critical.

The expected result of the above would be:

array([[0, 2, 4, 9],
       [2, 0, 2, 7],
       [4, 2, 0, 5],
       [9, 7, 5, 0]])

CodePudding user response:

You can use numpy.subtract.outer:

np.abs(np.subtract.outer(a, a))

array([[0, 2, 4, 9],
       [2, 0, 2, 7],
       [4, 2, 0, 5],
       [9, 7, 5, 0]])

Or equivalently use either of the followings:

np.abs(a - a[:, np.newaxis])
np.abs(a - a[:,  None])
np.abs(a - a.reshape((-1, 1)))
  • Related