首页 > 解决方案 > sympy:如何在评估之前打印矩阵产品?

问题描述

我有两个矩阵,比如说a, b我想打印(以可读的方式)

  1. <a> @ <b>,没有实际执行矩阵乘法
  2. 乘法的实际结果(由 sympy 执行)

有什么办法吗?

标签: pythonsympy

解决方案


您可以使用以下方法创建未评估的符号产品MatMulhttps ://docs.sympy.org/latest/modules/matrices/expressions.html#sympy.matrices.expressions.MatMul

In [16]: from sympy import *                                                                                                                   

In [17]: A = Matrix([[1, 2], [3, 4]])                                                                                                          

In [18]: B = Matrix([[5, 6], [7, 8]])                                                                                                          

In [19]: product = MatMul(A, B)                                                                                                                

In [20]: product                                                                                                                               
Out[20]: 
⎡1  2⎤ ⎡5  6⎤
⎢    ⎥⋅⎢    ⎥
⎣3  4⎦ ⎣7  8⎦

In [21]: product.doit()                                                                                                                        
Out[21]: 
⎡19  22⎤
⎢      ⎥
⎣43  50⎦

In [22]: Eq(product, product.doit())                                                                                                           
Out[22]: 
⎡1  2⎤ ⎡5  6⎤   ⎡19  22⎤
⎢    ⎥⋅⎢    ⎥ = ⎢      ⎥
⎣3  4⎦ ⎣7  8⎦   ⎣43  50⎦

推荐阅读