Search code examples
pythonmatrixsympysymbolic-math

Display a matrix with putting a common factor in sympy


I want to display a matrix with putting an extracted common factor on outside of the matrix after matrix calculation in sympy.

I wrote below code.

from sympy import *
a = symbols("a")
b = symbols("b")

A = Matrix([exp(I*a),exp(I*a)*exp(I*b)])
print simplify(A)

I got below output.

Matrix([
[      exp(I*a)],
[exp(I*(a + b))]])

However, I want to get below output.

exp(I*a)*Matrix([
[      1],
[exp(I*b)]])

I tried collect(A,exp(I*a)) and got follow error.

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.

I know a way to extract a common factor for a element of a matrix like follow link. https://github.com/sympy/sympy/issues/8442

But it's not my desire.

How should I do?


Solution

  • I do not think Sympy provides a function for the task you want. However, you can do this manually, as per the method proposed in the accepted answer of a similar question asked in the Mathematica SE (link).

    The idea is to extract the common factor of the polynomial elements via gcd and then use MatMul with the evaluate=False option in order to restrict Sympy from performing the scalar-matrix multiplication.

    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)]])