Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract all pairs of values from two arrays

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.

like image 970
jpcgandre Avatar asked Oct 16 '25 18:10

jpcgandre


1 Answers

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[None, :] - b[:, None]
print(res)
# [[3 4 5 6 7]
#  [2 3 4 5 6]
#  [1 2 3 4 5]
#  [0 1 2 3 4]]
like image 153
Roger Fan Avatar answered Oct 18 '25 07:10

Roger Fan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!