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?
Slice the vectors in a way that makes their shape match:
a[:, 0] * b
or
a * b[:, None]
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With