Python matrix multiplication operator

How to Multiply Two Matrices in Python

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.

Table of contents

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.

Читайте также:  Css table vertical scrolling

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 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:

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)

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 multiplying matrices in other programming languages, go to the article:

Have fun and happy researching!

Источник

NumPy @ Operator—Matrix Multiplication in Python

In NumPy, the @ operator means matrix multiplication.

For instance, let’s multiply two NumPy arrays that represent 2 x 2 matrices:

import numpy as np A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) product = A @ B print(product)

If you are familiar with matrix multiplication, I’m sure this answers your questions.

However, if you do not know what matrix multiplication means, or if you are interested in how the @ operator works under the hood, please stick around.

What Is Matrix Multiplication

A matrix is an array of numbers. It is a really popular data structure in data science and mathematics.

If you are unfamiliar with matrices, it is way too early to talk about matrix multiplication!

A 2x2 example matrix

Multiplying a matrix by a single number (scalar) is straightforward. Simply multiply each element in the matrix by the multiplier.

For example, let’s multiply a matrix by 2:

Multiplying a 2x2 matrix

When you multiply a matrix by another matrix, things get a bit trickier.

To multiply two matrices, take the dot product between each row on the left-hand side matrix and the column on the right-hand side matrix.

Multiplying two 2x2 matrices

Here are all the calculations made to obtain the result matrix:

For a comprehensive explanation, feel free to check a more thorough guide on matrix multiplication here.

To keep it short, let’s move on to matrix multiplication in Python.

Matrix Multiplication in Python

To write a Python program that multiplies matrices, you need to implement a matrix multiplication algorithm.

Here is the pseudocode algorithm for matrix multiplication for matrices A and B of size N x M and M x P.

Let’s implement this logic in our Python program where a nested list represents a matrix.

In this example, we multiply a 3 x 3 matrix by a 3 x 4 matrix to get a 3 x 4 result matrix.

# 3 x 3 matrix A = [ [12,7,3], [4 ,5,6], [7 ,8,9] ] # 3 x 4 matrix B = [ [5,8,1,2], [6,7,3,0], [4,5,9,1] ] N = len(A) M = len(A[0]) P = len(B[0]) # Pre-fill the result matrix with 0s. # The size of the result is 3 x 4 (N x P). result = [] for i in range(N): row = [0] * P result.append(row) for i in range(N): for j in range(P): for k in range(M): result[i][j] += A[i][k] * B[k][j] for r in result: print(r)
[114, 160, 60, 27] [74, 97, 73, 14] [119, 157, 112, 23]

As you might already know, matrix multiplication is quite a common operation performed on matrices.

Thus, it would be a waste of time to implement this logic in each project where you need matrix multiplication.

This is where the @ operator comes to the rescue.

The @ Operator in Python

As of Python 3.5, it has been possible to specify a matrix multiplication operator @ to a custom class.

This happens by overriding the special method called __matmul__.

The idea is that when you call @ for two custom objects, the __matmul__ method gets triggered to calculate the result of matrix multiplication.

For instance, let’s create a custom class Matrix, and override the matrix multiplication method to it:

class Matrix(list): # Matrix multiplication A @ B def __matmul__(self, B): self = A N = len(A) M = len(A[0]) P = len(B[0]) result = [] for i in range(N): row = [0] * P result.append(row) for i in range(N): for j in range(P): for k in range(M): result[i][j] += A[i][k] * B[k][j] return result # Example A = Matrix([[2, 0],[1, 9]]) B = Matrix([[3, 9],[4, 7]]) print(A @ B)

As you can see, now it is possible to call @ between two matrix objects to multiply them.

And by the way, you could also directly call the __matmul__ method instead of using the @ shorthand.

# Example A = Matrix([[2, 0],[1, 9]]) B = Matrix([[3, 9],[4, 7]]) print(A.__matmul__(B))

Awesome. Now you understand how matrix multiplication works, and how to override the @ operator in your custom class.

Finally, let’s take a look at multiplying matrices with NumPy using the @ operator.

Matrix Multiplication with NumPy: A @ B

In data science, NumPy arrays are commonly used to represent matrices.

Because matrix multiplication is such a common operation to do, a NumPy array supports it by default.

This happens via the @ operator.

In other words, somewhere in the implementation of the NumPy array, there is a method called __matmul__ that implements matrix multiplication.

For example, let’s matrix-multiply two NumPy arrays:

import numpy as np A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) product = A @ B print(product)

This concludes our example in matrix multiplication and @ operator in Python and NumPy.

Conclusion

Today you learned what is the @ operator in NumPy and Python.

To recap, as of Python 3.5, it has been possible to multiply matrices using the @ operator.

For instance, a NumPy array supports matrix multiplication with the @ operator.

To override/implement the behavior of the @ operator for a custom class, implement the __matmul__ method to the class. The __matmul__ method is called under the hood when calling @ between two objects.

Thanks for reading. Happy coding!

Источник

Оцените статью