Suppose I have a 1 x 5
vector:
vect = np.array([10, 20, 30, 40, 50])
and I have a 2 x 5
matrix:
mat = np.array([
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10]
])
and I would like to multiply together as so: 10 * [[1], [6]] = [[10], [60]]
for each column in the vector and each column in the matrix, outputting a d x n
vector. How can I efficiently accomplish this with numpy
? I have tried to investigate dot product, but it doesn't seem to accomplish my goals.
CodePudding user response:
vect * mat
does what you want, column-wise multiplication.
CodePudding user response:
A*B should do it
import numpy as np
A = 10*(np.arange(5) 1)
B = (np.arange(10) 1).reshape([2,5])
assert (A*B == np.array([[ 10, 40, 90, 160, 250],
[ 60, 140, 240, 360, 500]])).all()
CodePudding user response:
Following @John Zwinck's answer, if your idea is to multiply vect
1st column to mat
first column and so on, vect * mat
will be enough. On the other hand, if you have a second thought of using every column in vect
to multiply with every column in mat
, you can use numpy.tensordot
.
np.tensordot(vect,mat,axes=0)
Out[15]:
array([[[ 10, 20, 30, 40, 50],
[ 60, 70, 80, 90, 100]],
[[ 20, 40, 60, 80, 100],
[120, 140, 160, 180, 200]],
[[ 30, 60, 90, 120, 150],
[180, 210, 240, 270, 300]],
[[ 40, 80, 120, 160, 200],
[240, 280, 320, 360, 400]],
[[ 50, 100, 150, 200, 250],
[300, 350, 400, 450, 500]]])