简体   繁体   中英

Multiply matrix by array element-wise on numpy?

What I want is really simple but I can't figure out how to do it on numpy.

I have the following matrix:

M = [[1, 1, 1],
     [1, 1, 1],
     [1, 1, 1]]

And this array:

A = [1, 2, 3]

I want to multiply the matrix with each element on the array on a way to produce:

[[[1, 1, 1],
  [1, 1, 1],
  [1, 1, 1]],
 [[2, 2, 2],
  [2, 2, 2],
  [2, 2, 2]],
 [[3, 3, 3],
  [3, 3, 3],
  [3, 3, 3]]]

without any for loops, I want just a numpy function.

Using einsum

np.einsum('ij,k->kji', M, A)

array([[[1, 1, 1],
        [1, 1, 1],
        [1, 1, 1]],

       [[2, 2, 2],
        [2, 2, 2],
        [2, 2, 2]],

       [[3, 3, 3],
        [3, 3, 3],
        [3, 3, 3]]])
In [146]: M = np.ones((3,3),int)                                                                     
In [147]: M                                                                                          
Out[147]: 
array([[1, 1, 1],
       [1, 1, 1],
       [1, 1, 1]])
In [148]: A = np.array([1,2,3])   

broadcasted multiplication does this:

In [149]: A[:,None,None]*M                                                                           
Out[149]: 
array([[[1, 1, 1],
        [1, 1, 1],
        [1, 1, 1]],

       [[2, 2, 2],
        [2, 2, 2],
        [2, 2, 2]],

       [[3, 3, 3],
        [3, 3, 3],
        [3, 3, 3]]])

A is changed to (3,1,1); M is automatically broadcast to (1,3,3), together (3,3,3)

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