Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy broadcasting between matrix and vector? [duplicate]

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.

like image 835
Wei Avatar asked Jun 07 '26 11:06

Wei


1 Answers

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       ]])
like image 119
Divakar Avatar answered Jun 10 '26 19:06

Divakar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!