[Numpy-discussion] Multiplying Each Column of a Matrix by a Vector (Element-Wise)

Robert Kern robert.kern@gmail....
Wed Mar 14 12:48:48 CDT 2007


Alexander Michael wrote:
> Is there a clever way to multiply each column of a matrix by a vector
> *element-wise*? That is, the equivalent of (from some 1D v and 2D m):
> 
> r = numpy.empty_like(m)
> for i in range(m.shape[-1]):
>     r[...,i] = v*m[...,i]

  numpy.multiply(m, v[:,numpy.newaxis])

If m is actually just a shape-(n,m) array rather than a numpy.matrix object,
then you can spell that like so:

  m * v[:,numpy.newaxis]

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco


More information about the Numpy-discussion mailing list