[Numpy-discussion] Multiplying a matrix by a vector

Christopher Barker Chris.Barker at noaa.gov
Wed Feb 4 17:48:49 EST 2009


Simon Palmer wrote:
> I have a matrix and a vector which has the same number of elements as the
> matrix has rows.  I want to multiply each element in a row in the matrix by
> the corresponding element in the vector.

 >>> M = np.arange(6).reshape((2,3))
 >>> M
array([[0, 1, 2],
        [3, 4, 5]])
 >>> v = np.array((4,5)).reshape((-1,1)) # make it a column vector
 >>> v
array([[4],
        [5]])
 >>> M * v
array([[ 0,  4,  8],
        [15, 20, 25]])


you can also do it with np.newaxis:

 >>> v = np.array((4,5))
 >>> M * v[:,np.newaxis]
array([[ 0,  4,  8],
        [15, 20, 25]])



http://www.scipy.org/EricsBroadcastingDoc


If you are really working with a matrix, rather than a 2-d array, you 
may want to look at the np.matrix object.

-Chris


-- 
Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker at noaa.gov



More information about the NumPy-Discussion mailing list