Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simplify matrix expressions in SymPy?

Consider the following example

import sympy as sy
n = sy.symbols('n')
A = sy.MatrixSymbol("A",n,n)
B = sy.MatrixSymbol("B",n,n)
C = sy.MatrixSymbol("C",n,n)
M = A.inverse()*B.inverse() - A.inverse()*C*B.inverse()
B.inverse()*M.inverse()*A.inverse()

The example prints out B^-1*(A^-1*B^-1 - A^-1*C*B^-1)^-1*A^-1.

Can SymPy simplify the expression to (I-C)^-1? If not, how about any of the intermediate results, like collecting common factors in M?

like image 289
sarasvati119 Avatar asked Aug 21 '18 06:08

sarasvati119


People also ask

How do you simplify an expression in SymPy?

To simplify expressions using trigonometric identities, use trigsimp() . trigsimp() also works with hyperbolic trig functions. Much like simplify() , trigsimp() applies various trigonometric identities to the input expression, and then uses a heuristic to return the “best” one.

How do you simplify equations in Python?

simplify() method, we can simplify any mathematical expression. Parameters: expression – It is the mathematical expression which needs to be simplified. Returns: Returns a simplified mathematical expression corresponding to the input expression.

How do you evaluate an expression in SymPy?

To evaluate a numerical expression into a floating point number, use evalf . SymPy can evaluate floating point expressions to arbitrary precision. By default, 15 digits of precision are used, but you can pass any number as the argument to evalf .

How do you Diagonalize a matrix SymPy?

To diagonalize a matrix, use diagonalize . diagonalize returns a tuple , where is diagonal and M = P D P − 1 . lambda is a reserved keyword in Python, so to create a Symbol called , while using the same names for SymPy Symbols and Python variables, use lamda (without the b ).


1 Answers

The work around for this is using string converting on expression:

from sympy import *

n = symbols('n')
A = MatrixSymbol("A",n,n)
B = MatrixSymbol("B",n,n)
C = MatrixSymbol("C",n,n)
M = A.inverse()*B.inverse() - A.inverse()*C*B.inverse()
expression = B.inverse()*M.inverse()*A.inverse()

# convert expression to string then simplify
simplify_expression = simplify(str(expression))

pprint(simplify_expression)

Output:

 -1  
─────
C - 1
like image 171
Zaraki Kenpachi Avatar answered Sep 23 '22 12:09

Zaraki Kenpachi