Nickpick
Nickpick

Reputation: 6597

Calculating distance between each element of an array

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]])

Upvotes: 1

Views: 1392

Answers (1)

akuiper
akuiper

Reputation: 215057

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)))

Upvotes: 2

Related Questions