How to expand matrix expression in sympy
Question: Hi I'm trying to do a matrix multiplication and expand it afterwards. However,
`sympy` does not seem to support expansion of matrix equations. For example
Runge-Kutta 4 for matrices:

    
    
    from sympy import init_session
    init_session()
    from sympy import *
    
    A = MatrixSymbol('A', 3, 3)
    x = MatrixSymbol('x', 3, 1)
    dt = symbols('dt')
    
    k1 = A*x
    k2 = A*(x + S(1)/2*k1*dt)
    k3 = A*(x + S(1)/2*k2*dt)
    k4 = A*(x + k3*dt)
    final = dt*S(1)/6*(k1 + 2*k2 + 2*k3 + k4)
    final.expand()
    

With result

    
    
    Traceback (most recent call last)
    <ipython-input-38-b3ff67883c61> in <module>()
         12 final = dt*1/6*(k1+2*k2+2*k3+k4)
         13 
    ---> 14 final.expand()
    
    AttributeError: 'MatMul' object has no attribute 'expand'
    

I hope the expression can be expanded just like the scalar variant:

    
    
    A,x,dt = symbols('A x dt')
    k1 = A*x
    k2 = A*(x+k1*dt*S(1)/2)
    k3 = A*(x+k2*dt*S(1)/2)
    k4 = A*(x+k3*dt)
    final = x+dt*(S(1)/6)*(k1+k2+k3+k4)
    collect(expand((final)),x)
    

With result:

    
    
    x*(A**4*dt**4/24 + A**3*dt**3/8 + A**2*dt**2/3 + 2*A*dt/3 + 1)
    

Is it possible to alter a matrix expression likewise?

nicoguaro's answer takes the error away, but expands the the whole expression
into one matrix. As illustrated with the scalar example, not what I'm looking
for


Answer: I think that you can expand Matrix expressions. But what you have is not a
matrix but the multiplication of two symbolic matrices (Matsymbols). If you
turn your expression to a matrix you can get the expansion you wanted. See the
extra line below

    
    
    from sympy import init_session
    init_session()
    from sympy import *
    
    A = MatrixSymbol('A', 3, 3)
    x = MatrixSymbol('x', 3, 1)
    dt = symbols('dt')
    
    k1 = A*x
    k2 = A*(x + S(1)/2*k1*dt)
    k3 = A*(x + S(1)/2*k2*dt)
    k4 = A*(x + k3*dt)
    final = dt*S(1)/6*(k1 + k2 + k3 + k4)
    Matrix(final).expand()
    

