简体   繁体   中英

Multiplying two 2D numpy arrays to a 3D array

I've got two 2D numpy arrays called A and B , where A is M x N and B is M xn . My problem is that I wish to multiply each element of each row of B with corresponding row of A and create a 3D matrix C which is of size M xnx N , without using for -loops.

As an example, if A is:

A = np.array([[1, 2, 3],
              [4, 5, 6]])

and B is

B = np.array([[1, 2],
              [3, 4]])

Then the resulting multiplication C = A x B would look something like

C = [
     [[1, 2],
      [12, 16]],
     [[2, 4],
      [15, 20]],
     [[3, 6],
      [18, 24]]
     ]

Is it clear what I'm trying to achieve, and is it possible doing without any for -loops? Best, tingis

C=np.einsum('ij,ik->jik',A,B)

It is possible by creating a new axis in each array and transposing the modified A :

A[np.newaxis,...].T * B[np.newaxis,...]

giving:

array([[[ 1,  2],
        [12, 16]],

       [[ 2,  4],
        [15, 20]],

       [[ 3,  6],
        [18, 24]]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM