Fomalhaut
Fomalhaut

Reputation: 9825

Multiplication of two arrays in numpy

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?

Upvotes: 3

Views: 5934

Answers (3)

user ce
user ce

Reputation: 9

B = np.multiply.outer(x, y).T

link: http://pchanial.github.io/python-for-data-scientists/auto_examples/ufunc_matrices.html

here is a good tutorial for these question this address can help :Link

Upvotes: 0

Alex Riley
Alex Riley

Reputation: 177078

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

Upvotes: 7

Akavall
Akavall

Reputation: 86356

You can you use np.outer.

In [7]: x = np.array([1, 2])

In [8]: y = np.array([3, 4])

In [10]: np.outer(x,y).T
Out[10]: 
array([[3, 6],
       [4, 8]])

Upvotes: 3

Related Questions