I have two numpy arrays:
x = numpy.array([1, 2])
y = numpy.array([3, 4])
And I would like to create a matrix of elements products:
[[3, 6],
[4, 8]]
What is the easiest way to do this?
One way is to use the outer
function of np.multiply
(and transpose if you want the same order as in your question):
>>> np.multiply.outer(x, y).T
array([[3, 6],
[4, 8]])
Most ufuncs in NumPy have this useful outer
feature (add
, subtract
, divide
, etc.). As @Akavall suggests, np.outer
is equivalent for the multiplication case here.
Alternatively, np.einsum
can perform the multiplication and transpose in one go:
>>> np.einsum('i,j->ji', x, y)
array([[3, 6],
[4, 8]])
A third approach is to insert a new axis in one the arrays and then multiply, although this is a little more verbose:
>>> (x[:, np.newaxis] * y).T
array([[3, 6],
[4, 8]])
For those interested in performance, here are the timings of the operations, from quickest to slowest, on two arrays of length 15:
In [70]: x = np.arange(15)
In [71]: y = np.arange(0, 30, 2)
In [72]: %timeit np.einsum('i,j->ji', x, y)
100000 loops, best of 3: 2.88 µs per loop
In [73]: %timeit np.multiply.outer(x, y).T
100000 loops, best of 3: 5.48 µs per loop
In [74]: %timeit (x[:, np.newaxis] * y).T
100000 loops, best of 3: 6.68 µs per loop
In [75]: %timeit np.outer(x, y).T
100000 loops, best of 3: 12.2 µs per loop