In this post, we will see how to perform matrix multiplication using NumPy. Input parameters for numpy matrix multiplication are two array-like objects (it can be a numpy ndarray or python lists as well), and it produces the product of two matrices as output. Performing matrix multiplication on NumPy arrays is more efficient than performing matrix multiplication on python lists.

Let’s start by importing NumPy and performing a simple matrix multiplication using NumPy’s matrix multiplication np.matmul.

Python 3.8.5 (default, Mar 8 2021, 13:02:45)

[GCC 9.3.0] on linux2

Type “help”, “copyright”, “credits” or “license” for more information.

>>> a = np.array([[1, 2, 3],

... [4, 5, 6]])

>>> a.shape

(2, 3)

>>> b = np.array([[1, 1],

... [1, 1],

... [1, 1]])

>>> b.shape

(3, 2)

>>> c = np.matmul(a, b)

>>> c.shape

(2, 2)

>>> c

array([[ 6, 6],

[15, 15]])

The matrix multiplication in numpy follows the signature (n, k) * (k, m) -> (n, m). Sometimes, we need to perform a simple scalar multiplication of a matrix. To perform a scalar multiplication, the operator * can be used.

>>> a

array([[1., 1., 1.],

[1., 1., 1.]])

>>> a * 2

array([[2., 2., 2.],

[2., 2., 2.]])

np.matmul could also be used to perform the multiplication of multi-dimensional matrices. In the case of multi-dimensional matrices, the last two dimensions of the input matrices are considered for matrix multiplication.

>>> a.shape

(8, 3, 2)

>>> b = np.ones((8, 2, 5))

>>> b.shape

(8, 2, 5)

>>> c = np.matmul(a, b)

>>> c.shape

(8, 3, 5)

When operating on the inputs for np.matmul, numpy compares their shape to check whether the matrix multiplication between the two arrays is compatible or not. Ideally, the last dimension of matrix 1 should be the same as the second to last dimension of matrix 2. If they are not compatible, a Value Error is raised.

>>> a.shape

(2, 3)

>>> b = np.ones((1, 2))

>>> b.shape

(1, 2)

>>> np.matmul(a, b)

Traceback (most recent call last):

...

ValueError: matmul: Input operand 1 has a mismatch ...