By Marek Justyna


2018-08-10 12:04:32 8 Comments

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?

4 comments

@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

Related Questions

Sponsored Content

24 Answered Questions

[SOLVED] Difference between append vs. extend list methods in Python

60 Answered Questions

[SOLVED] Get all unique values in a JavaScript array (remove duplicates)

24 Answered Questions

[SOLVED] What is the difference between @staticmethod and @classmethod?

10 Answered Questions

49 Answered Questions

[SOLVED] How to merge two dictionaries in a single expression?

57 Answered Questions

[SOLVED] How do you split a list into evenly sized chunks?

21 Answered Questions

[SOLVED] Difference between __str__ and __repr__?

21 Answered Questions

[SOLVED] Peak detection in a 2D array

7 Answered Questions

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

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

5 Answered Questions

[SOLVED] Multiply several matrices in numpy

  • 2012-08-07 02:02:55
  • NNsr
  • 24578 View
  • 26 Score
  • 5 Answer
  • Tags:   python numpy

Sponsored Content