numpy subtract every row of matrix by vector

That works in numpy but only if the trailing axes have the same dimension. Here is an example of successfully subtracting a vector from a matrix:

In [27]: print m; m.shape
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
Out[27]: (4, 3)

In [28]: print v; v.shape
[0 1 2]
Out[28]: (3,)

In [29]: m  - v
Out[29]: 
array([[0, 0, 0],
       [3, 3, 3],
       [6, 6, 6],
       [9, 9, 9]])

This worked because the trailing axis of both had the same dimension (3).

In your case, the leading axes had the same dimension. Here is an example, using the same v as above, of how that can be fixed:

In [35]: print m; m.shape
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
Out[35]: (3, 4)

In [36]: (m.transpose() - v).transpose()
Out[36]: 
array([[0, 1, 2, 3],
       [3, 4, 5, 6],
       [6, 7, 8, 9]])

The rules for broadcasting axes are explained in depth here.

Leave a Comment