NumPy matrix multiplication behavior

You have the following:

In [14]: A = array([[1, 1], [3, 2], [-4, 1]]) In [15]: A Out[15]: array([[ 1, 1], [ 3, 2], [-4, 1]]) In [16]: x = array([1, 1]) In [17]: x Out[17]: array([1, 1]) In [18]: dot(A, x) Out[18]: array([ 2, 5, -3]) 

I was expecting a column because the dot () function is described as regular matrix multiplication.

Why does it return a string? This behavior seems very discouraging.

+4
source share
1 answer

x 1D vector, and as such, has no idea whether it is a row vector or a column vector. The same goes for the result of dot(A, x) .

Turn x into a 2D array and everything will be fine:

 In [7]: x = array([[1], [1]]) In [8]: x Out[8]: array([[1], [1]]) In [9]: dot(A, x) Out[9]: array([[ 2], [ 5], [-3]]) 

Finally, if you prefer to use a more natural matrix notation, convert A to numpy.matrix :

 In [10]: A = matrix(A) In [11]: A * x Out[11]: matrix([[ 2], [ 5], [-3]]) 
+3
source

All Articles