Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: How to elementwise-multiply two vectors, shape (n,1) and (n,)?

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?

like image 863
Nico Schlömer Avatar asked Mar 30 '12 17:03

Nico Schlömer


2 Answers

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

a[:, 0] * b

or

a * b[:, None]
like image 62
Sven Marnach Avatar answered Oct 25 '22 21:10

Sven Marnach


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.)

like image 33
NPE Avatar answered Oct 25 '22 19:10

NPE