[Numpy-discussion] how to multiply the rows of a matrix by a different number?

josef.pktd at gmail.com josef.pktd at gmail.com
Tue Mar 3 21:11:09 EST 2009


On Tue, Mar 3, 2009 at 8:53 PM, Jose Borreguero <borreguero at gmail.com> wrote:
> I guess there has to be an easy way for this. I have:
> M.shape=(10000,3)
> N.shape=(10000,)
>
> I want to do this:
> for i in range(10000):
> M[i]*=N[i]
> without the explicit loop
>

>>> M = np.ones((10,3))
>>> N = np.arange(10)
>>> N.shape
(10,)
>>> (N[:,np.newaxis]).shape
(10, 1)
>>> M*N[:,np.newaxis]
array([[ 0.,  0.,  0.],
       [ 1.,  1.,  1.],
       [ 2.,  2.,  2.],
       [ 3.,  3.,  3.],
       [ 4.,  4.,  4.],
       [ 5.,  5.,  5.],
       [ 6.,  6.,  6.],
       [ 7.,  7.,  7.],
       [ 8.,  8.,  8.],
       [ 9.,  9.,  9.]])

>>> M *= N[:,np.newaxis]
>>> M

Josef



More information about the NumPy-Discussion mailing list