Shin Yu Wu
Shin Yu Wu

Reputation: 1199

Numpy sum over all dimension of the outer product

If I want to implement this function: enter image description here

I know I can write a loop like this:

result = 0
for i in range(len(x)):
    for j in range(len(y)):
        result += x[i] * y[j]

But what if I want to use numpy to complete, how can I do?

Upvotes: 0

Views: 141

Answers (2)

Divakar
Divakar

Reputation: 221644

With np.einsum -

np.einsum('i,j->',x,y)

Or simply sum-reduce and then get product of the scalars -

x.sum()*y.sum()

Upvotes: 1

Nils Werner
Nils Werner

Reputation: 36795

You can use broadcasting for this

np.sum(x * y[:, None])

Upvotes: 0

Related Questions