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

Python – Divide each row by a vector

I have a 10×10 matrix and I want to divide each row of the matrix with the elements of a vector.

For eg:
Suppose I have a 3×3 matrix

1 1 1
2 2 2
3 3 3

and a vector [1, 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

Then this is the operation I wish to do:

1/1 1/2 1/3
2/1 2/1 2/3
3/1 3/2 3/3

i.e, divide the elements of a row by the elements of a vector(A python list)

I can do this using for loops. But, is there a better way to do this operation in python?

>Solution :

You should look into broadcasting in numpy. For your example this is the solution:

a = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]])
b = np.array([1, 2, 3]).reshape(1, 3)
c = a / b 
print(c)
>>> [[1.         0.5        0.33333333]
     [2.         1.         0.66666667]
     [3.         1.5        1.        ]]
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