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?
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]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With