Skip to content Skip to sidebar Skip to footer

Numpy: Add A Vector To Matrix Column Wise

a Out[57]: array([[1, 2], [3, 4]]) b Out[58]: array([[5, 6], [7, 8]]) In[63]: a[:,-1] + b Out[63]: array([[ 7, 10], [ 9, 12]]) This is row wise addition

Solution 1:

Add a newaxis to the end of a[:,-1], so that it has shape (2,1). Addition with b would then broadcast along the column (the second axis) instead of the rows (which is the default).

In [47]: b + a[:,-1][:, np.newaxis]
Out[47]: 
array([[ 7,  8],
       [11, 12]])

a[:,-1] has shape (2,). b has shape (2,2). Broadcasting adds new axes on the left by default. So when NumPy computes a[:,-1] + b its broadcasting mechanism causes a[:,-1]'s shape to be changed to (1,2) and broadcasted to (2,2), with the values along its axis of length 1 (i.e. along its rows) to be broadcasted.

In contrast, a[:,-1][:, np.newaxis] has shape (2,1). So broadcasting changes its shape to (2,2) with the values along its axis of length 1 (i.e. along its columns) to be broadcasted.


Post a Comment for "Numpy: Add A Vector To Matrix Column Wise"