Tingiskhan
Tingiskhan

Reputation: 1345

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 x n. 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 x n x 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

Upvotes: 4

Views: 2373

Answers (2)

yevgeniy
yevgeniy

Reputation: 908

You can use the NumPy Einstein summation function, einsum():

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

Upvotes: 6

Saullo G. P. Castro
Saullo G. P. Castro

Reputation: 58895

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

Upvotes: 4

Related Questions