1

When multiplication of two similar matrices 1*2 like [1,2], [3,5] is carried out using numpy.dot, it gives a result, when in fact it should be giving a shape and dimension error like while multiplying two similar arrays. What is going on under the hood?

a=[1,2]
b=[6,3]
result=[np.dot(b, a)]
print(result)

O/P= 12

But,

a=[[1,2]]
b=[[6,3]]
result=[np.dot(b, a)]
print(result)

Error:

O/P= ValueError: shapes (1,2) and (1,2) not aligned: 2 (dim 1) != 1 (dim 0)

Anubhav Singh
8,7395 gold badges28 silver badges47 bronze badges
asked Aug 10, 2019 at 13:32
1
  • To be picky, both of your inputs are lists. When converted to ndarray, which dot will do, they are 1d and 2d respectively. Commented Aug 10, 2019 at 16:32

2 Answers 2

3

As per the documentation here,

  • If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation).

  • If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred.

Case 1: a and b are 1-D arrays, so result is 1*6+2*3=12.

Case 2: a and b are 2-D arrays, so we will do matrix product of these two. It raises ValueError since the last dimension of a is not the same size as the second-to-last dimension of b.

answered Aug 10, 2019 at 13:51
0
0

Adding on to Anubhav Singh's correct answer, note that a matrix product of a row vector with a column vector returns a 1-by-1 matrix whose sole entry is the dot product of the two vectors, so in this case,

In [32]: a = np.array([[1,2]])
In [33]: b = np.array([[6,3]])
In [34]: a @ b.T
Out[34]: array([[12]])
In [35]: np.dot(a, b.T)
Out[35]: array([[12]])
In [36]: np.dot(a[0], b[0])
Out[36]: 12

This is why np.dot behaves the way it does.

answered Aug 10, 2019 at 14:40

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.