Matrices are one of the basic objects in mathematics. They allow you to represent and manipulate data as a table consisting of rows and columns. They are used to solve systems of linear equations, define matrix actions, transform coordinates, and much more.
In this article, we will describe several ways to create a matrix in Python. Additionally, we will look at some basic operations such as addition, multiplication, and defining an inverse matrix.
A matrix is a table of numbers used in math and engineering to represent data. Matrices take the form of a table consisting of rows and columns. Each element has a unique index that denotes the row and column in which it is located. For example, a 3x3 matrix will have 3 rows and 3 columns, and each element will have an index like (i, j)
, where i
is the row number and j
is the column number.
There are several ways to create a matrix in Python. There are some of them:
With lists. You can create a matrix using nested lists. Each nested list will correspond to one row. This is how you can create a square Python matrix:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
With NumPy. NumPy is a library for mathematical calculations and data processing. It has an Array
class that can be used to create a matrix:
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
If you need to perform standard mathematical operations with matrices, you should choose NumPy. It is easier to use, and all operations are already implemented in the library. But if you want to create your own methods, for example, for educational purposes, or if you plan to perform non-standard manipulations, use nested lists.
Now, let's look at matrix operations and work with them using nested lists and NumPy.
Here is a list of basic manipulations:
Addition. You can add two matrices if their dimensions are the same. Each element of the resulting matrix will equal the sum of the corresponding elements of the original matrices.
Subtraction. One matrix can be subtracted from another if their dimensions are the same. Each element of the resulting matrix will equal the difference of the corresponding elements of the original matrices.
Multiplication by a number. Each element of the final matrix will be equal to the product of the corresponding element of the original matrix by a number.
Multiplication of two matrices. Matrices can be multiplied if the number of columns of the first matrix equals the number of rows of the second matrix. The result will be a new matrix with the size corresponding to the number of rows of the first matrix and the number of columns of the second matrix. We will describe this operation in more detail later.
Matrix transpose. Transpose is an operation in which rows and columns are swapped. That is, the first column becomes the first row, the second column becomes the second row, and so on.
Inverse of a matrix. Matrix B will be the inverse matrix for matrix A if the result of the operation A*B is an identity matrix.
-
It is important to remember that when adding two matrices, their sizes must match.
Here is an example of addition using nested lists and loops:
matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix2 = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
result = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for i in range(len(matrix1)):
for j in range(len(matrix1[0])):
result[i][j] = matrix1[i][j] + matrix2[i][j]
print(result)
The result:
[[10, 10, 10], [10, 10, 10], [10, 10, 10]]
Here's a similar addition using the add()
method from the NumPy library:
import numpy as np
matrix1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix2 = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
result = np.add(matrix1, matrix2)
print(result)
The result:
[[10 10 10]
[10 10 10]
[10 10 10]]
In Python, you can perform matrix subtraction using a loop or the subtract()
method from the NumPy library. When subtracting, the dimensions must match.
Subtracting with a loop:
matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix2 = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
result = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for i in range(len(matrix1)):
for j in range(len(matrix1[0])):
result[i][j] = matrix1[i][j] - matrix2[i][j]
print(result)
The result:
[[-8, -6, -4], [-2, 0, 2], [4, 6, 8]]
Subtraction using the subtract()
method from the NumPy library:
import numpy as np
matrix1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix2 = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
result = np.subtract(matrix1, matrix2)
print(result)
The result:
[[-8 -6 -4]
[-2 0 2]
[ 4 6 8]]
In Python, multiplying a matrix by a number can be implemented using a loop or the dot()
method from the NumPy library.
When multiplying a matrix by a number, each element is multiplied by that number.
Multiplication using a loop:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
scalar = 2
result = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
result[i][j] = matrix[i][j] * scalar
print(result)
The result:
[[2, 4, 6], [8, 10, 12], [14, 16, 18]]
Here is an example of how the dot()
method from the NumPy library works with the same data:
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
scalar = 2
result = np.dot(matrix, scalar)
print(result)
The result:
[[ 2 4 6]
[ 8 10 12]
[14 16 18]]
You can also use the multiplication operation sign *
instead of the dot()
method:
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
scalar = 2
result = matrix * scalar
print(result)
The result:
[[ 2 4 6]
[ 8 10 12]
[14 16 18]]
In most cases, the dot()
method is faster than manually implemented loops.
This operation results in a new matrix with the number of rows of the first matrix and the number of columns of the second matrix. In matrix multiplication, the number of columns of the first matrix must match the number of rows of the second matrix. Each element of the new matrix is the sum of the product of the row elements of the first matrix and the column elements of the second matrix, as in the picture below:
As before, we implement the product using loops and NumPy.
Multiplication implemented on loops can look like this:
matrix1 = [[1, 2], [3, 4]]
matrix2 = [[5, 6], [7, 8]]
result = [[0, 0], [0, 0]]
for i in range(len(matrix1)):
for j in range(len(matrix2[0])):
for k in range(len(matrix2)): result[i][j] += matrix1[i][k] * matrix2[k][j]
print(result)
The result:
[[19, 22], [43, 50]]
NumPy uses the dot()
method for matrix multiplication:
import numpy as np
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
result = np.dot(matrix1, matrix2)
print(result)
The result:
[[19 22]
[43 50]]
The @
operation works similarly to the dot()
method:
import numpy as np
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
result = matrix1 @ matrix2
print(result)
The result:
[[19 22]
[43 50]]
Using the dot()
method or the @
operator gives faster results than using manually implemented loops.
Remember that the multiplication is a non-commutative operation, i.e., the order of matrix multiplication matters, and the result will be different if you rearrange them.
Transpose is an operation that turns the rows of the original matrix into the columns of the new matrix, and the columns into the rows.
In Python, you can perform a transpose using the T
property or the transpose()
method from the NumPy library.
An example of transpose using the T
property:
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
result = matrix.T
print(result)
The result:
[[1 4 7]
[2 5 8]
[3 6 9]]
And an example of transpose using the transpose()
method:
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
result = np.transpose(matrix)
print(result)
The result:
[[1 4 7]
[2 5 8]
[3 6 9]]
In both cases, the result is the same.
Using a loop, the transposition can be realized as follows:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
result = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
result[j][i] = matrix[i][j]
print(result)
The result:
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
This method can be slow and inefficient for large matrices, so NumPy is recommended for a faster and more efficient solution.
An inverse matrix is a matrix that, when multiplied by the original matrix, results in an identity matrix (with ones on the diagonal and zeros in the remaining cells).
In Python, you can find an inverse matrix using the inv()
method from the NumPy library.
import numpy as np
matrix = np.array([[1, 2], [3, 4]])
result = np.linalg.inv(matrix)
print(result)
The result:
[[-2. 1. ]
[ 1.5 -0.5]]
If the matrix does not have an inverse matrix, the inv()
method will raise the LinAlgError: Singular matrix exception
.
To check if a matrix has an inverse, use the det()
method from the NumPy library, which returns the determinant of the matrix. If the determinant is zero, the matrix is singular, and it has no inverse matrix:
import numpy as np
matrix = np.array([[1, 2], [3, 4]])
determinant = np.linalg.det(matrix)
if determinant == 0:
print("The matrix does not have an inverse.")
else:
result = np.linalg.inv(matrix)
print(result)
Finding the inverse matrix using loops can be quite complicated and time-consuming, especially for large matrices. Therefore, we recommend using NumPy.
Managed solution for Backend development
Matrices are an important concept in linear algebra and are often used in various fields, such as artificial intelligence, graphics, and optimization. Python provides many tools for working with matrices, including the NumPy library. Understanding matrices and their operations can help solve many practical problems in various fields.
If you want to build a web service using Python, you can rent a cloud server at competitive prices with Hostman.