Numpy: How to elementwise-multiply two vectors, sh

2020-07-08 07:25发布

问题:

Elementwise multiplication of two vectors is no problem if they both have the same shape, say both (n,1) or both (n,). If one vector has shape (n,1) and the other (n,), though, the *-operator returns something funny.

a = np.ones((3,1))
b = np.ones((3,))
print a * b

The resulting nxn-matrix contains A_{i,j}=a_i*b_j.

How can I do elementwise multiplication for the a and b then?

回答1:

Slice the vectors in a way that makes their shape match:

a[:, 0] * b

or

a * b[:, None]


回答2:

Add a second axis to b to that a and b have the same dimensions:

>>> a * b[:,np.newaxis]
array([[ 1.],
       [ 1.],
       [ 1.]])

Alternatively, transpose a so that broadcasting works:

>>> a.T * b
array([[ 1.,  1.,  1.]])

(You'd probably want to transpose the result.)