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

I have two arrays A and B in numpy. A contains Cartesian coordinates, each line is one point in three-dimensional space and has the form (r, 3). B has the form (r, n) and contains integers.

What I would like to do is multiply each element of B by each row in A so that the resulting array has the form (r, n, 3). 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 am sure that this can be done with help np.einsum, but I have tried this for quite some time and may fail.

+4
source share
1 answer

Use broadcasting-

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

np.einsum , ( @ajcr ) -

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

-

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]]])
+4

Source: https://habr.com/ru/post/1607240/


All Articles