Schach21
Schach21

Reputation: 450

How to calculate the outer sum (not product) between 2 (1D) vectors

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?

Upvotes: 0

Views: 650

Answers (2)

hpaulj
hpaulj

Reputation: 231385

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]])

Upvotes: 2

no comment
no comment

Reputation: 10239

Outer sum:

res = np.add.outer(a, b)

Upvotes: 1

Related Questions