Matrices are a big deal in almost everything that involves any kind of computation. Even fields like Computer Vision, Artificial Intelligence and Machine Learning rely heavily on Matrices. It thus makes sense, that SymPy, a Scientific Computation Library should have support for Matrices.
To learn more about other great features in SymPy, check out our SymPy Tutorials which cover all essential topics. If you are interested in practical applications of SymPy, check out our SymPy Project Series!
Creating Matrices in SymPy
The first way of creating Matrices in SymPy is through the use of the Matrix Class Constructor. This Class Constructor takes as a parameter, a 2D-List. Each one-dimensional list inside the 2D-List represents one row vector.
from sympy import symbols, Matrix, pretty_print
x, y = symbols("x y")
matrix = Matrix([[1, 2], [3, 4]])
print(matrix)
pretty_print(matrix)
There are two ways we can print this matrix object, either through the regular print function, or using pretty print from the SymPy library.
Matrix([[1, 2], [3, 4]])
⎡1 2⎤
⎢ ⎥
⎣3 4⎦
Be careful though. If you pass in a single list, then it will be treated as a column vector, not a row. This is to make it easier to create Column Vectors, as their use is more common.
print(Matrix([1, 2, 3]))
⎡1⎤
⎢ ⎥
⎢2⎥
⎢ ⎥
⎣3⎦
There are also some specialized constructors that we can use to create matrices. We will discuss these later on in the article.
Mutability of Matrices
Matrices in SymPy, unlike every other object in SymPy, are mutable. This means that they can be modified in place, instead of creating a new object with the modified values. The downside to this is that Matrix
cannot be used in places where immutability is required, such as inside other SymPy expressions or as keys to dictionaries. However, you can easily create an immutable version of a SymPy Matrix
, by using the ImmutableMatrix
Class.
Basic Operations with SymPy Matrices
Let’s take a look at several basic methods and functions that can be used on the SymPy Matrices to give us information about them.
Finding Shape of Matrix
The shape function can be used to determine the dimensions of a Matrix. It takes as parameter a matrix object, and returns a Tuple with the number of rows and columns.
from sympy import symbols, Matrix, shape
x, y = symbols("x y")
matrix1 = Matrix([[1, 2], [3, 4]])
matrix2 = Matrix([[1, 2], [3, 4], [5, 6]])
matrix3 = Matrix([[1, 2, 3], [4, 5, 6]])
print(shape(matrix1))
print(shape(matrix2))
print(shape(matrix3))
(2, 2)
(3, 2)
(2, 3)
Accessing Rows and Columns in a Matrix
To obtain a single column or row vector from a Matrix, we can use the row()
and col()
methods. Simply pass in the integer index of the row or column you want, and it will be returned to you. Remember that indexing starts from zero, so row(0)
refers to the first row.
matrix = Matrix([[1, 2], [3, 4], [5, 6]])
print(matrix.row(0))
print(matrix.row(2))
print(matrix.col(1))
Matrix([[1, 2]])
Matrix([[5, 6]])
Matrix([[2], [4], [6]])
Deletion of Matrix Rows and Columns
Similar to how row()
and col()
methods work, we also have row_del()
and col_del()
, which are used for the deletion of rows and columns.
Let’s start by trying to delete a row, and see how it effects the matrix.
from sympy import pretty_print, symbols, Matrix
x, y = symbols("x y")
matrix = Matrix([[1, 2], [3, 4], [5, 6]])
pretty_print(matrix)
matrix.row_del(1)
pretty_print(matrix)
⎡1 2⎤
⎢ ⎥
⎢3 4⎥
⎢ ⎥
⎣5 6⎦
⎡1 2⎤
⎢ ⎥
⎣5 6⎦
Now let’s try deleting a column.
from sympy import pretty_print, symbols, Matrix
x, y = symbols("x y")
matrix = Matrix([[1, 2], [3, 4], [5, 6]])
pretty_print(matrix)
matrix.col_del(0)
pretty_print(matrix)
⎡1 2⎤
⎢ ⎥
⎢3 4⎥
⎢ ⎥
⎣5 6⎦
⎡2⎤
⎢ ⎥
⎢4⎥
⎢ ⎥
⎣6⎦
It is important to note, that these operations are “in-place”, meaning a new object is not being created.
Insertion of Rows and Columns
Now let’s try adding some rows and columns to our Matrix. We’ll start off with a simple matrix, and expand it by adding an additional row and column. To do this, we use the row_insert()
and col_insert()
functions.
The first parameter in either function is the index at which you wish to add a row or column. The second Parameter is a Matrix object that will be added to the matrix we are calling the method on.
A very common mistake that could occur around here, is due to the dimensions of the matrices being added. Remember that there are rules are adding, subtracting and multiplying matrices. You must be aware of this otherwise SymPy will raise an error.
For example, a common pitfall is shown in the example below.
from sympy import pretty_print, symbols, Matrix
x, y = symbols("x y")
matrix = Matrix([[1, 2], [3, 4]])
pretty_print(matrix)
matrix = matrix.row_insert(2, Matrix([5, 6]))
pretty_print(matrix)
# ERROR!
Why does this return an error? It looks as though you are trying add a new row to a 2×2 matrix. It should logically expand to a 3×2 matrix, but that is not the case.
The answer is simple, because as mentioned earlier Matrix( [5, 6] ) creates a column vector, not a row vector. To correct this, do Matrix( [[5, 6]] ). Let’s try that again.
matrix = Matrix([[1, 2], [3, 4]])
pretty_print(matrix)
matrix = matrix.row_insert(2, Matrix([[5, 6]]))
pretty_print(matrix)
⎡1 2⎤
⎢ ⎥
⎣3 4⎦
⎡1 2⎤
⎢ ⎥
⎢3 4⎥
⎢ ⎥
⎣5 6⎦
Success! Let’s try this again, but with columns.
matrix = Matrix([[1, 2], [3, 4]])
pretty_print(matrix)
matrix = matrix.col_insert(2, Matrix([5, 6]))
pretty_print(matrix)
⎡1 2⎤
⎢ ⎥
⎣3 4⎦
⎡1 2 5⎤
⎢ ⎥
⎣3 4 6⎦
These two functions are not only for appending, but they can also insert rows and columns in the middle as well. Let’s take a look at an example.
matrix = Matrix([[1, 2], [3, 4]])
pretty_print(matrix)
matrix = matrix.row_insert(1, Matrix([[5, 6]]))
pretty_print(matrix)
(all we did was change the row index from 2 to 1)
⎡1 2⎤
⎢ ⎥
⎣3 4⎦
⎡1 2⎤
⎢ ⎥
⎢5 6⎥
⎢ ⎥
⎣3 4⎦
Unlike deletion, insertion of rows and cols is not-in-place. Meaning a new object is created each time a row or column is added. This is why we had to re-assign the value of the matrix when calling the function. Simply calling the method would not have effected it.
Mathematical Operations in SymPy Matrices
The few operations are very obvious and common. The addition, subtraction and multiplication of two matrices. Here are a few examples.
M = Matrix([[1, 2], [3, 4]])
N = Matrix([[5, 6], [7, 8]])
pretty_print(M - N)
pretty_print(M + N)
⎡-4 -4⎤
⎢ ⎥
⎣-4 -4⎦
⎡6 8 ⎤
⎢ ⎥
⎣10 12⎦
Now for multiplication. (Don’t forget the dimensions rule; you can’t just multiply any two matrices)
M = Matrix([[1, 2], [3, 4]])
N = Matrix([[5, 6], [7, 8]])
pretty_print(M * N)
⎡19 22⎤
⎢ ⎥
⎣43 50⎦
You can also multiply a matrix with regular numbers. It doesn’t have to be a matrix.
M = Matrix([[1, 2], [3, 4]])
pretty_print(M * 3)
⎡3 6 ⎤
⎢ ⎥
⎣9 12⎦
Finding the transpose and inverse of any matrix has been made easy by SymPy. For the transpose, use the .T
attribute. For the inverse, multiply a matrix by -1
.
M = Matrix([[1, 2], [3, 4]])
pretty_print(M.T)
pretty_print(M ** -1)
⎡1 3⎤
⎢ ⎥
⎣2 4⎦
⎡-2 1 ⎤
⎢ ⎥
⎣3/2 -1/2⎦
Calculating Determinant
Another useful feature that you don’t need to write your own code for, is the det()
function, which calculates and returns the determinant of a matrix.
M = Matrix([[1, 2], [3, 4]])
print(M.det())
-2
Matrix Constructors
Matrix Constructors are a bunch of methods used to both create and initialize SymPy Matrices in a unique manner. There are three in total, eye(), ones() and zeros().
eye(n), creates a square Identity matrix of size n x n
.
from sympy import pretty_print, eye, zeros, ones
pretty_print(eye(3))
⎡1 0 0⎤
⎢ ⎥
⎢0 1 0⎥
⎢ ⎥
⎣0 0 1⎦
ones(n, m), creates a matrix of size n x m
, with all values initialized to one.
from sympy import pretty_print, eye, zeros, ones
pretty_print(ones(2, 3))
⎡0 0⎤
⎢ ⎥
⎢0 0⎥
⎢ ⎥
⎣0 0⎦
zeros(n, m), creates a matrix of size n x m
, with all values initialized to zero.
from sympy import pretty_print, eye, zeros, ones
pretty_print(zeros(3, 2))
⎡1 1 1⎤
⎢ ⎥
⎣1 1 1⎦
This marks the end of the Matrices in SymPy Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.