Kevin
Kevin

Reputation: 3239

Numpy - Array dot product depending on order of input

I am trying to do a dot product and if I put a transposed array as the first parameter I get the correct answer (a single value) since it is essentially its a sum of products sum(a*b). But if I put the transposed array as the second parameter it gives me a 2x2 array. Why?

a = np.array([[1],[2]])

b = np.array([[3],[4]])

np.dot(a,b.T)
Out[208]: 
array([[3, 4],
       [6, 8]])

np.dot(a.T,b)
Out[209]: array([[11]])

np.dot(b.T, a)
Out[210]: array([[11]])

Upvotes: 0

Views: 2587

Answers (2)

victor
victor

Reputation: 1644

np.dot does not calculate the dot product of multiple arrays. It calculates the matrix multiplication of two ndarrays.

You can calculate the dot product of two vectors with np.dot because the dot product of vectors a and b is simply a^T * b. However, as with regular vectors, a^T * b and b * a^T result in two very different answers. The former calculates the dot product of the vectors, while the latter calculates the product of b and a^T.

Upvotes: 1

Ryan Stout
Ryan Stout

Reputation: 1028

If you multiply a k by 1 matrix (a vector) with a 1 by k matrix, you get a k by k matrix. If you multiply a 1 by k matrix with a k by 1 matrix, you get a 1 by 1 matrix.

Upvotes: 2

Related Questions