'How to define some symbols as matrices in Sympy?

I am trying to create symbolic functions from an input file that is parsed, and the resulting expressions can be pretty huge. Once the mathematical expressions are created using sympy, I then try to use lambdify to generate a function which can take matrices in the form of ndarrays. The problem is the following, the matrices I want to substitute into the expression can vary in size and so I cannot start with a matrix with predefined size.

Thus, the workaround is to use normal symbols which can then be replaced with numpy ndarray matrices. Which worked when the matrices are diagonal, but not any more as I need to use non-diagonal matrices. Thus, I want to use @ operator in the terms with matrices and * for multiplication with numbers or diagonal matrices. I tried using some other methods, but I ended up creating my own function F(x,y) which is then substituted using string manipulation, and the recreating the sympy expression using parse_expr which then is converted into function using lambdify. This is particularly messy, and I was looking for a more elegant solution. Thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source