Reputation: 542
I am so confused about Numpy array. Let's say I have two Numpy arrays.
a = np.array([[1,2], [3,4], [5,6]])
b = np.array([[1,10], [1, 10]])
My interpretations of a
and b
are 3x2 and 2x2 matrices, i.e,
a = 1 2 b = 1 10
3 4 1 10
5 6
Then, I thought it should be fine to do a * b
since it is a multiplication of 3x2 and 2x2 matrices. However, it was not possible and I had to use a.dot(b)
.
Given this fact, I think my intepretation of Numpy array is not right. Can anyone let me know how I should think of Numpy array? I know that I can do a*b
if I convert a
and b
into np.matrix. However, looking at other's code, it seems that people are just fine to use Numpy array as matrix, so I wonder how I should understand Numpy array in terms of matrix.
Upvotes: 0
Views: 118
Reputation: 795
For numpy arrays, the *
operator is used for element by element multiplication of arrays. This is only well defined if both arrays have the same dimensions. To illuminate *
-multiplication, note that element by element multiplication with the identity matrix will not return the same matrix
>>> I = np.array([[1,0],[0,1]])
>>> B = np.array([[1,2],[3,4]])
>>> I*B
array([[ 1, 0],
[ 0, 4]])
Using the numpy function dot(a,b)
produces the typical matrix multiplication.
>>> dot(I,B)
array([[ 1, 2],
[ 3, 4]])
Upvotes: 2
Reputation: 8418
np.dot
is probably what you're looking for?
a = np.array([[1,2], [3,4], [5,6]])
b = np.array([[1,10], [1, 10]])
np.dot(a,b)
Out[6]:
array([[ 3, 30],
[ 7, 70],
[ 11, 110]])
Upvotes: 1