Reputation: 4677
Why is it in numpy
possible to multiply a 2x2
matrix by a 1x2
row vector?
import numpy as np
I = np.array([[1.0, 0.0], [0.0, 1.0]])
x = np.array([2.0,3.0])
In: I * x
Out: array([[ 2., 0.], [ 0., 3.]])
Transposing x
does also make no sense. A row vector stays a row vector?
In: x.T
Out: array([ 2., 3.])
From a mathematical point of view the representation is very confusing.
Upvotes: 3
Views: 6124
Reputation: 31672
If you check shape of you x
you will see (2,) which means numpy array:
In [58]: x.shape
Out[58]: (2,)
If you need 1x2 vector you could use reshape
:
x_vec = x.reshape(2,1)
In [64]: x_vec.shape
Out[64]: (2, 1)
Then you could use numpy dot
method for multiplication:
In [68]: I.dot(x_vec)
Out[68]:
array([[ 2.],
[ 3.]])
But dot
also works without reshaping:
In [69]: I.dot(x)
Out[69]: array([ 2., 3.])
You also could use np.matmul
to do that:
In [73]: np.matmul(I, x_vec)
Out[73]:
array([[ 2.],
[ 3.]])
Upvotes: 2
Reputation: 8689
Numpy arrays are not vectors. Or matrices for that matters. They're arrays.
They can be used to represent vectors, matrices, tensors or anything you want. The genius of numpy however is to represent arrays, and let the user decide on their meaning.
One operation defined on arrays is the (termwise) multiplication. In addition, broadcasting lets you operate on arrays of different shapes by 'extending' it in the missing dimensions, so your multiplication is really the (termwise) multiplication of:
[[1.0, 0.0], [0.0, 1.0]] * [[2.0, 2.0], [3.0, 3.0]]
If you want to use the dot product, in the matricial sense, you should use the .dot
method, which does exactly that: interpret its inputs as vectors/matrices/tensors, and do a dot product.
Upvotes: 9
Reputation: 10564
If you are using Python 3.5 you can use the @
operator.
In [2]: I@x
Out[2]: array([ 2., 3.])
Upvotes: 2