user2909415
user2909415

Reputation: 1029

Numpy: multiplying matrix elements with array of matrices

I need to multiply the elements of a, let's say, 2x2 matrix, x, with a matrix, y, whose elements are 2x2 matrices. When I use the conventional numpy multiplication it takes the entire matrix, x, and multiples it with each matrix in y. I have been searching the numpy doc. for something that will replicate this:

>>> x = np.array([[1, 0], [0, 1]])
>>> x
array([[1, 0],
       [0, 1]])
>>> y = np.ones((2, 2, 2, 2))
>>> y
array([[[[ 1.,  1.],
         [ 1.,  1.]],
    [[ 1.,  1.],
     [ 1.,  1.]]],
   [[[ 1.,  1.],
     [ 1.,  1.]],
    [[ 1.,  1.],
     [ 1.,  1.]]]])
>>> multiply(x,y)
[[[[1, 1],
   [1, 1]],
  [[0, 0],
   [0, 0]]],
 [[[0, 0],
   [0, 0]],
  [[1, 1],
   [1, 1]]]]

Upvotes: 1

Views: 204

Answers (1)

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

Reputation: 58865

EDIT: From the comments of @Dalek and @DSM it seems that actually what you want is:

np.einsum('ij, ijkl-> ijkl', x, y)

Upvotes: 3

Related Questions