我希望显示一个矩阵,在对象中进行矩阵计算后,将提取的公因子放在矩阵外部。
我在下面写了代码。
from sympy import *
a = symbols("a")
b = symbols("b")
A = Matrix([exp(I*a),exp(I*a)*exp(I*b)])
print simplify(A)
我得到了以下输出。
Matrix([
[ exp(I*a)],
[exp(I*(a + b))]])
但是,我想要低于输出。
exp(I*a)*Matrix([
[ 1],
[exp(I*b)]])
我尝试收集(A,exp(I * a))并得到跟随错误。
Traceback (most recent call last):
File "<ipython-input-65-834f4c326df4>", line 1, in <module>
runfile('C:/Anaconda2/Programs/test/untitled44.py', wdir='C:/Anaconda2/Programs/test')
File "C:\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 699, in runfile
execfile(filename, namespace)
File "C:\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 74, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)
File "C:/Anaconda2/Programs/test/untitled44.py", line 14, in <module>
collect(A,exp(I*a))
File "C:\Anaconda2\lib\site-packages\sympy\simplify\simplify.py", line 451, in collect
if expr.is_Mul:
File "C:\Anaconda2\lib\site-packages\sympy\matrices\matrices.py", line 3084, in __getattr__
"%s has no attribute %s." % (self.__class__.__name__, attr))
AttributeError: MutableDenseMatrix has no attribute is_Mul.
我知道一种方法来提取像跟随链接这样的矩阵元素的公因子。 https://github.com/sympy/sympy/issues/8442
但这不是我的愿望。
我该怎么办?
答案 0 :(得分:3)
我认为Sympy
不能为您想要的任务提供功能。但是,您可以按照Mathematica SE(link)中提出的类似问题的接受答案中提出的方法手动执行此操作。
我们的想法是通过gcd
提取多项式元素的公因子,然后将MatMul
与evaluate=False
选项一起使用,以限制Sympy
执行标量 - 矩阵乘法。
import sympy as sp
a, b = sp.symbols('a, b')
A = sp.Matrix([sp.exp(sp.I * a), sp.exp(sp.I * a) * sp.exp(sp.I * b)])
g = sp.gcd(tuple(A))
A_v2 = sp.MatMul(g,(A/g),evaluate = False)
print(A_v2)
exp(I*a)*Matrix([ [ 1], [exp(I*b)]])