3

Given an array a of shape (n, k1) and an array b of shape (n, k2), I would like to compute all outer products of a[i] and b[i]. This

import numpy

n = 3

a = numpy.random.rand(n, 7)
b = numpy.random.rand(n, 11)

out = numpy.array([
    numpy.outer(a[i], b[i]) for i in range(n)
    ])

print(out.shape)  # (n, 7, 11)

does the trick, but it contains a Python loop which slows things down for large n.

Can the outer products be computed at once?

Nico Schlömer
  • 46,467
  • 24
  • 178
  • 218
  • Which algorithm can calculate them without calculate n times? Rather to find another algorithm, I think creating a `numpy.array` with fixed size and then using multiple processing to accelerate calculation is a better solution. For example, calculate `numpy.outer` with `numexpr`. – Sraw Sep 08 '17 at 09:53

1 Answers1

2
np.einsum('ij,ik->ijk', a, b)

Or, using broadcasting,

a[:,:,np.newaxis] * b[:,np.newaxis,:]
cs95
  • 330,695
  • 80
  • 606
  • 657
Warren Weckesser
  • 102,583
  • 19
  • 173
  • 194