Subtract all pairs of values from two arrays

筅森魡賤 提交于 2019-12-19 09:43:58

问题


I have two vectors, v1 and v2. I'd like to subtract each value of v2 from each value of v1 and store the results in another vector. I also would like to work with very large vectors (e.g. 1e6 size), so I think I should be using numpy for performance.

Up until now I have:

import numpy
v1 = numpy.array(numpy.random.uniform(-1, 1, size=1e2))
v2 = numpy.array(numpy.random.uniform(-1, 1, size=1e2))
vdiff = []
for value in v1:
    vdiff.extend([value - v2])

This creates a list with 100 entries, each entry being an array of size 100. I don't know if this is the most efficient way to do this though. I'd like to calculate the 1e4 desired values very fast with the smallest object size (memory wise) possible.


回答1:


You're not going to have very much fun with the giant arrays that you mentioned. But if you have more reasonably-sized matrices (small enough that the result can fit in memory), the best way to do this is with broadcasting.

import numpy as np

a = np.array(range(5, 10))
b = np.array(range(2, 6))

res = a[np.newaxis, :] - b[:, np.newaxis]
print(res)
# [[3 4 5 6 7]
#  [2 3 4 5 6]
#  [1 2 3 4 5]
#  [0 1 2 3 4]]



回答2:


np.subtract.outer

You can use np.ufunc.outer with np.subtract and then transpose:

a = np.array(range(5, 10))
b = np.array(range(2, 6))

res1 = np.subtract.outer(a, b).T
res2 = a[np.newaxis, :] - b[:, np.newaxis]

assert np.array_equal(res1, res2)

Performance is comparable between the two methods.



来源:https://stackoverflow.com/questions/26076576/subtract-all-pairs-of-values-from-two-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!