Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiplying an array of matrices with a vector

I have an array of matrices in which I would like to multiply each matrix by a different number. I tried it this way:

>>> import numpy as np
>>> c = np.array([[[1, 2],[3, 4]],[[1, 2],[3, 4]]])
>>> d = np.array([0.1, 0.2])
>>> d*c
array([[[ 0.1,  0.4],
        [ 0.3,  0.8]],

       [[ 0.1,  0.4],
        [ 0.3,  0.8]]])

While my intention is to get this result -

>>> np.array([d[0]*c[0], d[1]*c[1]])
array([[[ 0.1,  0.2],
        [ 0.3,  0.4]],

       [[ 0.2,  0.4],
        [ 0.6,  0.8]]])

What is the NumPy'iest way to do it?

like image 956
Ohm Avatar asked Mar 09 '26 15:03

Ohm


1 Answers

You need an extra couple of axes:

In [22]: d[:,None,None] * c
Out[22]: 
array([[[ 0.1,  0.2],
        [ 0.3,  0.4]],

       [[ 0.2,  0.4],
        [ 0.6,  0.8]]])

d[:,None,None] has shape (2,1,1) which is broadcast across your c array of shape (2,2,2) to multiply each block of c by the corresponding element of d.

like image 179
xnx Avatar answered Mar 11 '26 05:03

xnx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!