#### [SOLVED] 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?

#### @M.r_L 2018-08-10 12:30:57

Let :

``````>>> A = np.array([[1,1,1], #Shape = (2,3)
[1,1,1]])
>>> A
Out[3]:
array([[1, 1, 1],
[1, 1, 1]])
>>>B = np.array([2, 3])  # shape = (2,)
``````

Both have different shapes so we can't do matrix multiplication(element-wise) So we can do `A.T` which will convert the shape of the `A` to `(3,2)`

``````>>> (A.T * B).T
Out[7]:
array([[2, 2, 2],
[3, 3, 3]])
``````

#### @Daniel F 2018-08-10 12:13:15

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

#### @jpp 2018-08-10 12:10:33

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]])
``````

#### @Marek Justyna 2018-08-10 12:12:54

That excacly I am looking for! Element-wise multiplication :) Thank you!

#### @Talha Irfan 2018-08-10 12:09:26

your question is defying the rules of mathematics. Matrix A and B cannot be multiplied together because the number of columns in A does not equal the number of rows in B. In this case, the multiplication of these two matrices is not defined

#### @Sqoshu 2018-08-10 12:10:35

I think that by 'multiplication' he actually meant `doing something to the matrices`, but he didn't formulate it right so it's unknown what happens in certain situations.

#### @Talha Irfan 2018-08-10 12:37:41

well yes, I guess

### [SOLVED] How to iterate through two lists in parallel?

• 2009-11-02 21:26:24
• Nathan Fellman
• 417942 View
• 573 Score
• Tags:   python iterator