Skip to content Skip to sidebar Skip to footer

Subtract A Column Vector From Matrix At Specified Vector Of Columns Using Only Broadcast

I want to subtract a column vector from a numpy matrix using another vector which is index of columns where the first column vector needs to be subtracted from the main matrix. Fo

Solution 1:

One can use bincount and outer

>>> M - np.outer(V, np.bincount(I, None, M.shape[1]))
array([[ 0,  1,  0, -3],
       [ 1,  0,  0, -3],
       [ 0,  0,  1, -3],
       [ 1,  0,  0, -3],
       [ 0,  0,  0, -2]])

or subtract.at

>>>out = M.copy()>>>np.subtract.at(out, (np.s_[:], I), V[:, None])>>>out
array([[ 0,  1,  0, -3],
       [ 1,  0,  0, -3],
       [ 0,  0,  1, -3],
       [ 1,  0,  0, -3],
       [ 0,  0,  0, -2]])

Solution 2:

Post a Comment for "Subtract A Column Vector From Matrix At Specified Vector Of Columns Using Only Broadcast"