0

It seems like np.einsum should do the trick, but I haven't been able to make it work.

An example:

a = np.arange(3)
b = np.arange(2)

#that computes the outer product
res = np.einsum('i,j->ij',a,b)

#The resulting array I am looking for is:
out = [[0, 1], [1, 2], [2, 3]]
#or its transpose. 

I've been searching and all functions seem to point towards outer product, not outer sum. A for loop would do the job, but I'd like to have something a lot more efficient than that.

Does anyone know how to implement the outer sum using np.einsum or something else?

Schach21
  • 412
  • 4
  • 21

2 Answers2

2
In [610]: a = np.arange(3)
     ...: b = np.arange(2)
     ...: 
In [611]: np.add.outer(a,b)
Out[611]: 
array([[0, 1],
       [1, 2],
       [2, 3]])

By adding a dimension to a (3,1), we can use the addition operator. Look up broadcasting for details.

In [612]: a[:,None]+b
Out[612]: 
array([[0, 1],
       [1, 2],
       [2, 3]])
hpaulj
  • 221,503
  • 14
  • 230
  • 353
1

Outer sum:

res = np.add.outer(a, b)
no comment
  • 6,381
  • 4
  • 12
  • 30
  • Yes, after posting I found that function. In general, this answer explains better the property that general numpy functions have an outer property: https://stackoverflow.com/questions/33848599/performing-outer-addition-with-numpy – Schach21 Aug 28 '21 at 05:28