Matrix multiplication is a binary operation that produces a matrix from two matrices. Multiplying matrices is ubiquitous in mathematics, physics and computer science. You can perform matrix multiplication in Python using nested loops, list comprehension or the dot() method from numpy.

This tutorial will go through how to multiply two matrices in Python with the help of code examples.


Matrix Multiplication Explained

A matrix is a rectangular arrangement of numbers into rows and columns. We refer to each number as a matrix element or entry in a matrix.

For example, the matrix below has two rows and three columns. The element in the second row in the first column of the matrix is 4.

To perform matrix multiplication, the number of columns in the first matrix must equal the number of rows in the second matrix. The resultant matrix will have the number of rows of the first and the number of columns of the second matrix. Below is an example of matrix multiplication.

Matrix elements
Matrix elements
Matrix Multiplication
Matrix multiplication

Let’s look at an example of matrix multiplication between a 2×3 and a 3×2 matrix. The result will be a 2×2 matrix, and the green highlight shows how we perform a row by column multiplication.

Matrix multiplication numerical example
Matrix multiplication numerical example

Matrix Multiplication in Python Without NumPy

Matrix Multiplication in Python Using Nested Loop

Creating a Matrix in Python Without NumPy

In Python, we can create a matrix as a nested list, which is a list within a list. Each element in a nested list is a row of the matrix, for example:

X = [[10, 3, 5],
[7, 9, 2],
[11, 6, 9]]

represents a 3×3 matrix. Putting each row on a separate line in your code will improve readability.

Creating a Matrix in Python With NumPy

We can create a matrix using NumPy by passing a nested list to the array() method, for example:

import numpy as np

X = np.array([[10, 3, 5],
[7, 9, 2],
[11, 6, 9]])

print(X)
[[10  3  5]
 [ 7  9  2]
 [11  6  9]]

Indexing a Matrix in Python

We can select the first row in X using X[0] and select the element in the first row of the first column using X[0][0]. Let’s look at an example of multiplying two matrices using a nested loop.

# Program to multiply two matrices using nested loops

# 3 x 3 matrix

X = [[10, 3, 5],
[7, 9, 2],
[11, 6, 9]]

# 3 x 4 matrix

Y = [[8, 5, 1, 10],
[7, 6, 3, 1],
[2, 4, 9, 1]]

# result is a 3 x 4 matrix

result = [[0, 0, 0, 0],
[0,0,0,0],
[0,0,0,0]]

# Iterate over rows in X

for i in range(len(X)):

    # Iterate through columns in Y

    for j in range(len(Y[0])):

        # Iterate through the rows of Y

        for k in range(len(Y)):

            result[i][j] += X[i][k] * Y[k][j]

for r in result:
    
    print(r)

In the above program, we use nested for loops to iterate over each row and column and calculate the sum of the products for each row by column multiplication. Let’s run the code to get the result:

[111, 88, 64, 108]
[123, 97, 52, 81]
[148, 127, 110, 125]

Matrix Multiplication in Python Using Nested List Comprehension

Nested list comprehension performs a list comprehension within a list comprehension, resulting in a nested list. The syntax for nested list comprehension is:

new_list = [[expression for item in list] for item in list]

We can use nested list comprehension to multiply two matrices, similar to the nested loop method. Let’s look at an example:

# Program to multiply two matrices using list comprehension

# 3 x 3 matrix

X = [[10, 3, 5],
[7, 9, 2],
[11, 6, 9]]

# 3 x 4 matrix

Y = [[8, 5, 1, 10],
[7, 6, 3, 1],
[2, 4, 9, 1]]

# result is a 3 x 4 matrix

result = [[sum(a*b for a,b in zip(X_row, Y_col)) for Y_col in zip(*Y)] for X_row in X]

for r in result:

    print(r)

In the above program, we are iterating over the columns in matrix Y and the rows in matrix X to calculate the sum of the products of each row by column multiplication. We use zip() and the unpacking operator to get the columns of matrix Y. To do the sum of products for every row in the nested list; we need the for X_row in X as the second part of the nested list comprehension. Let’s run the code to get the result:

[111, 88, 64, 108]
[123, 97, 52, 81]
[148, 127, 110, 125]

Both nested loop approaches are computationally expensive and do not scale well to large matrices. For larger matrix operations, it is better to use numerical libraries like NumPy. The following examples will discuss using the NumPy methods dot() and matmul().

Matrix Multiplication in Python with NumPy

Matrix Multiplication in Python Using numpy.dot()

We can use NumPy’s dot() function to multiply two matrices. Let’s look at an example:

import numpy as np 

# Program to multiply two matrices using np.dot()

# 3 x 3 matrix

X = [[10, 3, 5],
[7, 9, 2],
[11, 6, 9]]

# 3 x 4 matrix

Y = [[8, 5, 1, 10],
[7, 6, 3, 1],
[2, 4, 9, 1]]

# Result is a 3 x 4 matrix

result = np.dot(X,Y)

print(result)

We replace the nested loop or nested list comprehension with an np.dot() call in the above code. This approach is much faster and more concise. Let’s run the code to get the result:

[[111  88  64 108]
 [123  97  52  81]
 [148 127 110 125]]

We can also convert the nested lists to NumPy arrays and then call the dot() method as shown below:

import numpy as np 

# Program to multiply two matrices using np.dot()

# 3 x 3 matrix

X = np.array([[10, 3, 5],
[7, 9, 2],
[11, 6, 9]])

# 3 x 4 matrix

Y = np.array([[8, 5, 1, 10],
[7, 6, 3, 1],
[2, 4, 9, 1]])

# Result is a 3 x 4 matrix

result = X.dot(Y)

print(result)
[[111  88  64 108]
 [123  97  52  81]
 [148 127 110 125]]

Matrix Multiplication in Python Using numpy.matmul()

We can use NumPy’s matmul() function to multiply two matrices. Let’s look at an example:

import numpy as np 

# Program to multiply two matrices using np.matmul()

# 3 x 3 matrix

X = np.array([[10, 3, 5],
[7, 9, 2],
[11, 6, 9]])

# 3 x 4 matrix

Y = np.array([[8, 5, 1, 10],
[7, 6, 3, 1],
[2, 4, 9, 1]])

# Result is a 3 x 4 matrix

result = np.matmul(X,Y)

print(result)

We replace the nested loop or nested list comprehension with an np.matmul() call in the above code. Let’s run the code to get the result:

[[111  88  64 108]
 [123  97  52  81]
 [148 127 110 125]]

Summary


Congratulations on reading to the end of this tutorial! You have gone through the fundamentals of matrix multiplication and how to do it in Python with nested loops, nested list comprehension and the NumPy methods dot() and matmul(). The most efficient way to do matrix multiplication is to use NumPy’s built-in methods; remember to import the library before using the methods.


For further reading on matrix manipulation in Python, go to the article: How to Find the Transpose of a Matrix in Python.

For further reading on NumPy arrays, go to the article: How to Solve Python ValueError: operands could not be broadcast together with shapes

Go to the online courses page on Python to learn more about coding in Python for data science and machine learning.

Have fun and happy researching!