Florian
Florian

Reputation: 1824

Compute pairwise differences between two vectors in numpy?

I have two vectors and I would like to construct a matrix of their pairwise differences. Currently I do this:

import numpy as np
a = np.array([1,2,3,4])
b = np.array([3,2,1])
M = a.reshape((-1,1)) - b.reshape((1,-1))

This certainly works, but I wonder if it's really the intended way of doing things. The readability of the line is suboptimal; one has to think a while what the reshapes are doing. Can this be improved? Is there another "cleaner" way of achieving the same?

Upvotes: 5

Views: 3116

Answers (1)

Arya McCarthy
Arya McCarthy

Reputation: 8829

There's an efficient way to do this that doesn't require you to manually reshape, using numpy's ufunc (universal function) features. Each ufunc, including np.subtract, has a method called outer, which does what you want. (documentation)

outer applies the computation (in this case, np.subtract) to all pairs.

>>> import numpy as np
>>> a = np.array([1,2,3,4])
>>> b = np.array([3,2,1])
>>> M = np.subtract.outer(a, b)
>>> M
array([[-2, -1,  0],
       [-1,  0,  1],
       [ 0,  1,  2],
       [ 1,  2,  3]])
>>>

Let's confirm that it matches your intended result.

>>> # This is how `M` was defined in the question:
>>> M = a.reshape((-1,1)) - b.reshape((1,-1))
>>> M
array([[-2, -1,  0],
       [-1,  0,  1],
       [ 0,  1,  2],
       [ 1,  2,  3]])

Upvotes: 10

Related Questions