Artem Pianykh
Artem Pianykh

Reputation: 1181

Matrix multiplication behavior in NumPy

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 dot() function is described as an ordinary matrix multiplication.

Why does it return a row instead? This behaviour seems very discouraging.

Upvotes: 4

Views: 407

Answers (1)

NPE
NPE

Reputation: 500157

x a 1D vector, and as such has no notion of whether it's a row vector or a column vector. Same goes for the result of dot(A, x).

Turn x into a 2D array, and all will be well:

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 more natural matrix notation, convert A to numpy.matrix:

In [10]: A = matrix(A)

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

Upvotes: 3

Related Questions