Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply each row of one array with each element of another array in numpy

I have two arrays A and B in numpy. A holds cartesian coordinates, each row is one point in 3D space and has the shape (r, 3). B has the shape (r, n) and holds integers.

What I would like to do is multiply each element of B with each row in A, so that the resulting array has the shape (r, n, 3). So for example:

# r = 3
A = np.array([1,1,1, 2,2,2, 3,3,3]).reshape(3,3)
# n = 2
B = np.array([10, 20, 30, 40, 50, 60]).reshape(3,2)

# Result with shape (3, 2, 3):
# [[[10,10,10], [20,20,20]],
# [[60,60,60], [80,80,80]]
# [[150,150,150], [180,180,180]]]

I'm pretty sure this can be done with np.einsum, but I've been trying this for quite a while now and can't get it to work.

like image 830
rldw Avatar asked Sep 14 '15 09:09

rldw


People also ask

How do you multiply each element in an array NumPy?

You can use np. multiply to multiply two same-sized arrays together. This computes something called the Hadamard product. In the Hadamard product, the two inputs have the same shape, and the output contains the element-wise product of each of the input values.

How do I multiply an element by NumPy element?

multiply() in Python. numpy. multiply() function is used when we want to compute the multiplication of two array. It returns the product of arr1 and arr2, element-wise.

How do you multiply two arrays together?

C = A . * B multiplies arrays A and B by multiplying corresponding elements. The sizes of A and B must be the same or be compatible. If the sizes of A and B are compatible, then the two arrays implicitly expand to match each other.


1 Answers

Use broadcasting -

A[:,None,:]*B[:,:,None]

Since np.einsum also supports broadcasting, you can use that as well (thanks to @ajcr for suggesting this concise version) -

np.einsum('ij,ik->ikj',A,B)

Sample run -

In [22]: A
Out[22]: 
array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])

In [23]: B
Out[23]: 
array([[10, 20],
       [30, 40],
       [50, 60]])

In [24]: A[:,None,:]*B[:,:,None]
Out[24]: 
array([[[ 10,  10,  10],
        [ 20,  20,  20]],

       [[ 60,  60,  60],
        [ 80,  80,  80]],

       [[150, 150, 150],
        [180, 180, 180]]])

In [25]: np.einsum('ijk,ij->ijk',A[:,None,:],B)
Out[25]: 
array([[[ 10,  10,  10],
        [ 20,  20,  20]],

       [[ 60,  60,  60],
        [ 80,  80,  80]],

       [[150, 150, 150],
        [180, 180, 180]]])
like image 161
Divakar Avatar answered Nov 15 '22 00:11

Divakar