Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 917
Tingiskhan Avatar asked Jan 08 '23 17:01

Tingiskhan


1 Answers

C=np.einsum('ij,ik->jik',A,B)
like image 177
yevgeniy Avatar answered Jan 11 '23 16:01

yevgeniy