简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM