How to embbed a matrix symbolic form from sympy in a formatted string?

Viewed 95

In a notebook, printing a sympy matrix is not difficult

enter image description here

However this doesn't work for formatted strings:

enter image description here

How can I do to maintain the symbolic representation in the formatted string?


Textual code:

import sympy
sympy.init_printing()
C = sympy.Matrix([[2, 3], [4, 5]])
display (C)
display (f'{C} x {C} = {C*C}')
1 Answers
In [1]: C = Matrix([[2,3],[4,5]])

In [2]: C
Out[2]: 
⎡2  3⎤
⎢    ⎥
⎣4  5⎦

The f'{}' formating uses either the repr or str format of the C object:

In [3]: repr(C)
Out[3]: 'Matrix([\n[2, 3],\n[4, 5]])'

In [4]: str(C)
Out[4]: 'Matrix([[2, 3], [4, 5]])'

It's a python formatting operation that doesn't pay attention to sympy's display methods.

https://docs.sympy.org/latest/tutorial/printing.html documents sympy printing, though I don't off hand see ideas that will help you.

To display the whole thing as a sympy expression, the whole thing has to be rendered as whole; we can't forat each piece separately:

In [9]: display(C, 'x', C, '=', C*C)
⎡2  3⎤
⎢    ⎥
⎣4  5⎦
'x'
⎡2  3⎤
⎢    ⎥
⎣4  5⎦
'='
⎡16  21⎤
⎢      ⎥
⎣28  37⎦

===

As per comment:

In [11]: Eq(MatMul(C, C), C*C)
Out[11]: 
⎡2  3⎤ ⎡2  3⎤   ⎡16  21⎤
⎢    ⎥⋅⎢    ⎥ = ⎢      ⎥
⎣4  5⎦ ⎣4  5⎦   ⎣28  37⎦
Related