Search code examples
pythonnumpymathsympy

Solve matrix and vector multiplication with parameters instead of values (preferably in python)


I want to look at some vector operations and see which matrix elements go into which vector, e.g. if I define a matrix with elements

mat = [["a11", "a12"], ["a21", "a22"]]

and a vector

vec = ["v1", "v2"]

then I'm looking for some module / library that gives me the result when I calclulate the product:

res = mat*vec = ["a11"*"v1" + "a12"*"v2", "a21"*"v1" + "a22"*"v2"]

I know this is easy to do if all the parameters are actual numbers with numpy and of course I could work this out by hand, but if the operations becomes more complex it would be nice to have a way to automatically generate the resulting vector as a parameter equation.

Bonus points if the equation gets simplified, if e.g. the result has +"a11" - "a11" somewhere and reduces this to 0.

Is this at all possible to do in python? Wolfram Alfa gets me what I'm looking for, but I also need some operations on input data so a way to do this with a script would be great.


Solution

  • You've tagged your question "numpy", but numpy is a library for numeric calculations.

    For symbolic calculations, use library sympy instead.

    import sympy
    
    v1, v2, a11, a12, a21, a22 = sympy.symbols('v1 v2 a11 a12 a21 a22')
    
    m = sympy.Matrix([[a11, a12], [a21, a22]])
    v = sympy.Matrix([v1, v2])
    
    u = m @ v
    
    print(u)
    
    # Matrix([
    # [a11*v1 + a12*v2],
    # [a21*v1 + a22*v2]])
    

    Pretty much any operators that are available in standard python are available in sympy. Two important things to keep in mind:

    • never use math functions with sympy, instead use their sympy equivalent, for instance sympy.sqrt instead of math.sqrt for square root;
    • sometimes you need to convert to sympy first before applying an operator, for instance 1 / 3 will be interpreted as standard python division and be rounded to 0.3333333333333333, but sympy.S(1) / 3 or sympy.Rational(1, 3) will represent the exact fraction one third.