One option is to use the Sympy Matrices module . SymPy is a symbolic math library for Python that is fully compatible with NumPy, especially for simple matrix manipulation tasks like this.
>>> from sympy import symbols, Matrix
>>> from numpy import trace
>>> x, y, a, b = symbols('x y a b')
>>> M = Matrix(([x, y], [a, b]))
>>> M
Matrix([
[x, y],
[a, b]])
>>> trace(M)
b + x
>>> M.dot(M)
[a*y + x**2, a*b + a*x, b*y + x*y, a*y + b**2]
source
share