0

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]])
ddejohn
  • 8,775
  • 3
  • 17
  • 30
Nickpick
  • 6,163
  • 16
  • 65
  • 116
  • Does this answer your question? [How to construct a matrix of all possible differences of a vector in numpy](https://stackoverflow.com/questions/26053914/how-to-construct-a-matrix-of-all-possible-differences-of-a-vector-in-numpy) – ddejohn Sep 22 '21 at 16:39

1 Answers1

2

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)))
Psidom
  • 209,562
  • 33
  • 339
  • 356
  • OP mentions that speed is critical. Perhaps post some benchmarks for the different techniques? – ddejohn Sep 22 '21 at 16:31
  • @ddejohn I wouldn't expect a big difference between either of these methods, since they basically do the same calculation under the hood. – Psidom Sep 22 '21 at 16:40
  • Then why mention them when `np.ufunc.outer()` is much more explicit and readable? I also did memory tests and yeah, they're all equivalent. I dunno I guess I don't really see the point in offering inferior alternatives (from a readability standpoint, since that's all it comes down to). – ddejohn Sep 22 '21 at 16:52
  • @ddejohn I don't think they are inferior alternatives. They are more concise and also a good way to learn numpy broadcasting concept, which is ubiquitous to efficiently apply numpy techniques. – Psidom Sep 22 '21 at 16:55