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

<p>I wrote below code.</p>

<pre><code>from sympy import *
a = symbols("a")
b = symbols("b")

A = Matrix([exp(I*a),exp(I*a)*exp(I*b)])
print simplify(A)
</code></pre>

<p>I got below output.</p>

<pre><code>Matrix([
[      exp(I*a)],
[exp(I*(a + b))]])
</code></pre>

<p>However, I want to get below output.</p>

<pre><code>exp(I*a)*Matrix([
[      1],
[exp(I*b)]])
</code></pre>

<p>I tried collect(A,exp(I*a)) and got follow error.</p>

<pre><code>Traceback (most recent call last):

  File "&lt;ipython-input-65-834f4c326df4&gt;", line 1, in &lt;module&gt;
    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 &lt;module&gt;
    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.
</code></pre>

<p>I know a way to extract a common factor for a element of a matrix like follow link.
<a href="https://github.com/sympy/sympy/issues/8442" rel="nofollow">https://github.com/sympy/sympy/issues/8442</a></p>

<p>But it's not my desire.</p>

<p>How should I do?</p>

<p>I do not think <code>Sympy</code> 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 (<a href="http://mathematica.stackexchange.com/questions/44500/factor-a-vector">link</a>). </p>

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

<pre><code>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)
</code></pre>

<blockquote>
<pre><code>exp(I*a)*Matrix([
[       1],
[exp(I*b)]])
</code></pre>
</blockquote>

python matrix sympy symbolic-math