2

I created two arrays using numpy:

import numpy as np    
a = np.array([[1, 5, 7], [6, 8, 9]])
b = np.array([[1, 8, 8], [5, 8, 0], [8, 9, 0]])
np.dot(a, b)

Now, while performing np.dot(a, b) I am getting the error :

ValueError: operands could not be broadcast together with shapes (2,3) (3,3) .

Normally, value error is raised if the last dimension of a is not the same size as the second-to-last dimension of b. What is wrong with my code?

kmario23
  • 57,311
  • 13
  • 161
  • 150

1 Answers1

6

Your code works fine. Please note that when the inputs to np.dot() are matrices, np.dot() performs matrix multiplication

In [18]: a = np.array([[1, 5, 7], [6, 8, 9]])
    ...: b = np.array([[1, 8, 8], [5, 8, 0], [8, 9, 0]])
    ...: 

# @ is equivalent to `np.dot()` and `np.matmul()` in Python 3.5 and above
In [19]: a @ b
Out[19]: 
array([[ 82, 111,   8],
       [118, 193,  48]])


In [20]: (a @ b).shape
Out[20]: (2, 3)

# sanity check!
In [22]: a @ b == np.matmul(a, b)
Out[22]: 
array([[ True,  True,  True],
       [ True,  True,  True]], dtype=bool)

Note on @: It was introduced in Python 3.5 as a dedicated infix operator for matrix multiplication

This is because some confusion existed whether * operator does matrix multiplication or element-wise multiplication. So, to eliminate confusion, a dedicated operator @ was designated for matrix multiplication. So,

* performs element-wise multiplication
@ performs matrix multiplication (dot product)


kmario23
  • 57,311
  • 13
  • 161
  • 150
  • The easiest way to perform a hassle-free dot product with two-dimensional NumPy arrays `a` and `b` is `(a * b).sum(axis=-1)` – brethvoice Jul 21 '21 at 13:22