4

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!

Ehsan
  • 10,716
  • 1
  • 15
  • 28
Abs
  • 1,536
  • 1
  • 14
  • 28

2 Answers2

6

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]]
Ehsan
  • 10,716
  • 1
  • 15
  • 28
1

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.

Frank Yellin
  • 3,214
  • 1
  • 7
  • 15
  • Good answer, but I am curious in what sense would that be more generalizable? – Ehsan Nov 05 '20 at 06:28
  • If instead the arrays were (100, m) and (100, n), the solution is still the same idea. However I'd have to search the documentation to find if there were some version of np.add that used the first index, or some keyword argument to np.add.outer. – Frank Yellin Nov 05 '20 at 08:04
  • `np.add.ufunc` works for any number of dimensions and returns the output dimensions in the same order as input. – Ehsan Nov 05 '20 at 23:29