Search code examples
pythonmatrixsympysymbolic-math

Mix of Matrix and Scalar symbols


Is there a way to mix Matrix symbols and scalar symbols in Sympy?

I want to make a scalar function that takes vectors and scalars for example:

import sympy as sy
v=sy.MatrixSymbol('v',3,1)
f=v.T*v+5

I receive an error saying: TypeError: Mix of Matrix and Scalar symbols

I know I could use a symbol for each of the dot products that I'm going to do, but that's not very elegant.


Solution

  • The sympy code checks that all symbols in an addition operation (sum) that involves Matrices, are Matrices. That's why you get an error.

    You could circumvent this by doing:

    >>> v.T*v + 5*sym.Identity(1)
    # 5*I + v'*v
    

    If you intend to do this operation frequently, you might want to consider changing it into a lambda expression or such.