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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With