Search code examples
pythonsympysymbolic-math

Can sympy simplify block matrix expressions?


Consider the following example: (I attempt to compute the matrix product involving a block matrix)

import sympy as sy

k, n = sy.symbols('k,n')
A = sy.MatrixSymbol("A", n, n)
B = sy.MatrixSymbol("B", n, k)
M = sy.BlockMatrix([[A * B, A]])
A.inverse() * M

which will output

A^-1*Matrix([[A*B, A]])

Is there a way to simplify/expand/cancel this to the more reader-friendly form of Matrix([[B, I]])?


Solution

  • Yes, using the function block_collapse which evaluates block-matrix expressions down to the level of blocks.

    sy.block_collapse(A.inverse()*M)   
    

    returns Matrix([[B, I]])