Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient multiplying matrices with different shapes in numpy

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?

like image 940
Marek Justyna Avatar asked Sep 29 '26 13:09

Marek Justyna


2 Answers

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]])
like image 71
jpp Avatar answered Oct 01 '26 03:10

jpp


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

like image 32
Daniel F Avatar answered Oct 01 '26 03:10

Daniel F