Numpy: How to multiply two vectors in different ways, the form (n, 1) and (n,)?

Elemental multiplication of two vectors is not a problem if they both have the same shape, say, both (n, 1) and both (n,). If one vector has the form (n, 1) and the other (n,), however, 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 elementary multiplication for a and b and then?

+6
source share
2 answers

Draw the vectors so that their shape matches:

 a[:, 0] * b 

or

 a * b[:, None] 
+15
source

Add a second axis to b to which a and b are the same dimensions:

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

Alternatively, transpose a so that the broadcast works:

 >>> aT * b array([[ 1., 1., 1.]]) 

(You probably want to reschedule the result.)

+4
source

Source: https://habr.com/ru/post/912070/


All Articles