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 rows with corresponding columns in Python (cuPy/Numpy)?

I need to multiply each row with a column at the corresponding row-index. Consider the graphics below in which I have a 3 x 3 matrix. The required operation is to multiply the row[0] of matrix with col[0] of transposed_matrix, row[1] of matrix with col[1] of transposed_matrix, and so on.

enter image description here

Question: How can achieve it in cupPy/Numpy Python in a smart way (i.e. without using for-loops)?

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

>Solution :

If you have a 3X3 array:

import numpy as np
A = np.array([[1, 2, 3],
             [4, 5, 6],
             [7, 8, 9]])

you can do:

A@A.T

but, it will produce 3X3 output

array([[ 14,  32,  50],
       [ 32,  77, 122],
       [ 50, 122, 194]])

so, if you want your desired output:


np.diag(A@A.T)

#array([ 14,  77, 194])

When the matrices are different:

B = np.array([
    [4,3,2],
    [6,9,7],
    [8,4,3]
])

np.diag(A@B.T)

#output
array([ 16, 111, 115])
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