I have two matrices A and B:
>>>A
[[1,1,1]
[1,1,1]]
>>>B
[2, 3]
I want to multiply them efficiently to get such result:
>>> A*B
[[2,2,2]
[3,3,3]]
I am looking for a more efficient solution than iterate in a loop. Can anyone help?
You can use np.multiply to multiply element-wise with broadcasting:
A = np.array([[1,1,1],
[1,1,1]])
B = np.array([2, 3])
res = np.multiply(A, B[:, None])
print(res)
array([[2, 2, 2],
[3, 3, 3]])
Simplest way is just (A*B.T).T But it's probably better to get used to broadcasting:
A * B[:, None]
This is functionally identical to @jpp's answer with np.multiply, but a little shorter to write
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