3

I am learning numpy linear algerba, and I want to perform a simple calculation: I have:

m = np.array([[1,2],
              [3,4],
              [5,6]]
v = np.array([10,20,30])

what I want to calculate/output:

[ [1/10, 2/10], 
  [3/20, 4/20],
  [5/30, 6/30]]

basically to perform a element-wise division between each row of m and each element of v

I can probably do that via some for loop, but I'd like to know the "proper" ways of doing it.

I am sensing it has something to do with the broadcasting but that's it.

Thanks.

David Arenburg
  • 91,361
  • 17
  • 137
  • 196
Wei
  • 341
  • 2
  • 14

1 Answers1

2

You need to align the elements of v to the first axis of m. One way to do so would be to extend v to a 2D array with np.newaxis/None and then broadcasting comes into play when performing elementwise division. Also, since both inputs are integer arrays and you are performing division, you need to convert one of them into a float before performing the elementwise divison. Thus, the final implementation would be -

m/v[:,None].astype(float)

You can avoid the conversion to floating point array at user-level if you use NumPy's true division func np.true_divide that takes care of the floating point conversion under the hood. So, the implementation with it would be -

np.true_divide(m,v[:,None])

Sample run -

In [203]: m
Out[203]: 
array([[1, 2],
       [3, 4],
       [5, 6]])

In [204]: v
Out[204]: array([10, 20, 30])

In [205]: m/v[:,None].astype(float)
Out[205]: 
array([[ 0.1       ,  0.2       ],
       [ 0.15      ,  0.2       ],
       [ 0.16666667,  0.2       ]])

In [206]: np.true_divide(m,v[:,None])
Out[206]: 
array([[ 0.1       ,  0.2       ],
       [ 0.15      ,  0.2       ],
       [ 0.16666667,  0.2       ]])
Divakar
  • 218,885
  • 19
  • 262
  • 358