Symbolic matrices

SymPy · Practical · 12 min

Symbolic linear algebra gives exact closed forms for small systems, Jacobians and parameterised models.

Matrix([[1, 2], [3, 4]]) creates a matrix; entries can be numbers, symbols or any expression. Helper constructors include eye(n), zeros(m, n), ones(m, n) and diag(...). A flat list gives a column vector.

Operators follow linear algebra: A * B and A @ B are matrix products, A**-1 or A.inv() the inverse, A.T the transpose. The most used methods are:

  • A.det(), A.rank(), A.rref() (reduced row echelon form plus pivot columns),
  • A.eigenvals() (dict of eigenvalue to multiplicity) and A.eigenvects(),
  • A.nullspace(), A.columnspace(),
  • A.LUsolve(b) or A.solve(b) for A x = b,
  • A.subs(...), A.applyfunc(simplify) to work entry-wise,
  • Matrix(fs).jacobian(vars) for Jacobians.

Everything is exact, which is the point and the cost. Symbolic determinants and inverses grow explosively with size; a 6x6 fully symbolic inverse can take a very long time and produce enormous output. For numeric matrices beyond a handful of rows, use NumPy.

Matrix is mutable (you can assign A[0, 1] = 5), which also means it is not hashable. Use ImmutableMatrix when you need to put a matrix inside other expressions or use it as a dict key.

Example

from sympy import Matrix, symbols, eye, simplify

a = symbols("a")
A = Matrix([[1, 2], [3, 4]])
print(A * A)          # Matrix([[7, 10], [15, 22]])
print(A.inv())        # Matrix([[-2, 1], [3/2, -1/2]])
print(A.det())        # -2

M = Matrix([[a, 1], [1, a]])
print(M.eigenvals())  # {a - 1: 1, a + 1: 1}
print(M.det())        # a**2 - 1

print(Matrix([[1, 2, 3], [2, 4, 6]]).rref())  # (Matrix([[1, 2, 3], [0, 0, 0]]), (0,))
b = Matrix([5, 11])
print(A.solve(b))     # Matrix([[1], [2]])

x, y = symbols("x y")
print(Matrix([x**2 * y, x + y]).jacobian([x, y]))  # Matrix([[2*x*y, x**2], [1, 1]])

Remember

  • Matrix entries can be any expression; * and @ are matrix products
  • det, inv, rref, eigenvals, solve, jacobian cover most needs
  • Symbolic cost explodes with size; use NumPy for big numeric matrices

Watch out for

  • Trying to invert a large fully symbolic matrix and waiting forever.

Check yourself

  1. What does Matrix([[1, 2], [3, 4]]) * Matrix([1, 1]) give?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.sympy.org/latest/tutorials/intro-tutorial/matrices.html