1

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]]]]
9
  • 1
    what is exactly your question? Commented Sep 19, 2014 at 14:35
  • How do I multiply each element of matrix x as if it were a scalar with the corresponding matrix in y. basically I need something that will replicate the multiply function that I gave in the example code. Commented Sep 19, 2014 at 14:41
  • @user2909415 It seems you are looking for np.tensordot(x, y, axes=[[0, 1], [0, 1]]), but your question is unclear... what is the expected result? Commented Sep 19, 2014 at 14:46
  • 1
    Ones and zeros make for confusing examples for multiplication since is 1: just 1, or maybe 1*1, or maybe 1*1 + 0*1, etc.. Commented Sep 19, 2014 at 15:00
  • 1
    @ Yes it does. Thank you for your help though. Commented Sep 19, 2014 at 15:53

1 Answer 1

3

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

np.einsum('ij, ijkl-> ijkl', x, y)
Sign up to request clarification or add additional context in comments.

2 Comments

I think he/she is looking for a way to multiply each element of matrix x in each element of matrix y, which is a 2x2 matrix, the example of the requested answer is given in the question.
IIUC the einsum version of what the OP is looking for is np.einsum('ij,ijkl->ijkl', x, y). I haven't had my coffee yet though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.