19

I was wondering how to create a matrix and compute its inverse using SymPy in Python?

For example, for this symbolic matrix:

Georgy
  • 12,464
  • 7
  • 65
  • 73
Tim
  • 1
  • 141
  • 372
  • 590

2 Answers2

19

If your question was: How to compute the inverse of a matrix M in sympy then:

M_inverse = M.inv()

As for how to create a matrix:

M = Matrix(2,3, [1,2,3,4,5,6])

will give you the following 2X3 matrix:

1 2 3

4 5 6

See: http://docs.sympy.org/0.7.2/modules/matrices/matrices.html

vlsd
  • 945
  • 6
  • 18
snakile
  • 52,936
  • 62
  • 169
  • 241
  • 1
    What is the difference between `M.inv()` and `Inverse(M)`? – Karlo Aug 02 '17 at 15:22
  • 1
    @Karlo I'm not sure, if related, but have a look: https://stackoverflow.com/questions/50854803/difference-between-eye-and-identity-in-sympy – yokke Jul 28 '18 at 18:18
11

Here is example of how we can compute inverse for a symbolic matrix (taking the one from the question):

import sympy as sym


# Not necessary but gives nice-looking latex output
# More info at: http://docs.sympy.org/latest/tutorial/printing.html
sym.init_printing()

sx, sy, rho = sym.symbols('sigma_x sigma_y rho')
matrix = sym.Matrix([[sx ** 2, rho * sx * sy], 
                     [rho * sx * sy, sy ** 2]])

Now printing the inverse matrix.inv() will give:
                                      enter image description here

which can be further simplified like sym.simplify(matrix.inv()):
                                                enter image description here

Georgy
  • 12,464
  • 7
  • 65
  • 73