How to get "dot addition" in numpy similar to dot product?

Viewed 234

I'm somewhat new to numpy and am strugging with this problem. I have two 2-dimensional numpy arrays:

array1 = [a1, a2, ..., an]
array2 = [b1, b2, ..., am]

a1, a2, b1, and b2 are all 1-d arrays with exactly 100 floats in them. However, array1 and array2 have different lengths. So array1 and array2 have shapes (n, 100) and (m, 100) respectively, where n and m are arbitrary lengths.

I'd like to perform some kind of modified dot product between them so I can output the following matrix:

array([[ a1+b1, a1+b2, a1+b3, ...],
       [ a2+b1, a2+b2, a2+b3, ...],
       [ a3+b1, a3+b2, a3+b3, ...],
       [...]])

I understand that np.dot(array1, array2.T) gets me really close. It just gives me a1•b1 instead of a1+b1 in the desired output array.

What's the most computationally efficient way for me to get my desired array with numpy? Thanks in advance!

2 Answers

use np.outer ufunc which is for this purpose:

np.add.outer(array1,array2)

example:

array1 = np.array([1,2,3])
array2 = np.array([1,2])

output:

[[2 3]
 [3 4]
 [4 5]]

As a slightly different, and slightly more generalizable solution than the one above.

If you make the first array look like it's (m, 1, 100) and the second array look like its (1, n, 100) and then add these two together, you'll get what you want via numpy's broadcasting rules.

But that's easy: m[:,None,:] + n[None,:,:]. You can easily extend this to any sorts of operations between m and n.

Related