Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get "dot addition" in numpy similar to dot product? [duplicate]

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!

like image 448
Abs Avatar asked Mar 01 '23 22:03

Abs


1 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]]
like image 199
Ehsan Avatar answered May 03 '23 16:05

Ehsan