Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to multiply each row from one matrix to every rows to another matrix on Python?

A and B matrices will be different when i run the program

A = np.array([[1, 1, 1], [2, 2, 2]])
B = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]])

The output matrix (C) should be the same dimension as matrix A.
As title says, I’m trying to multiply each row from one matrix (A) to every rows to another matrix (B) and would like to sum them.

For example,
Dimension of C = (2,3)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

C = [[A(0)*B(0) + A(1)*B(0)], [A(0)*B(1) + A(1)*B(1)],[A(0)*B(1) + A(1)*B(1)]]

I would like to know if there is a numpy function does that.

>Solution :

Use numpy broadcasting:

C = (A * B[:, None]).sum(axis=1)

Output:

>>> C
array([[3, 3, 3],
       [6, 6, 6],
       [9, 9, 9]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading