Search code examples
pythonsympysymbolic-math

How to take element-wise logarithm of a matrix in sympy?


Working with a sympy Matrix or numpy array of sympy symbols, how does one take the element-wise logarithm?

For example, if I have:

m=sympy.Matrix(sympy.symbols('a b c d'))

Then np.abs(m) works fine, but np.log(m) does not work ("AttributeError: log").

Any solutions?


Solution

  • Use Matrix.applyfunc:

    In [6]: M = sympy.Matrix(sympy.symbols('a b c d'))
    
    In [7]: M.applyfunc(sympy.log)
    Out[7]:
    ⎡log(a)⎤
    ⎢      ⎥
    ⎢log(b)⎥
    ⎢      ⎥
    ⎢log(c)⎥
    ⎢      ⎥
    ⎣log(d)⎦
    

    You can't use np.log because that does a numeric log, but you want the symbolic version, i.e., sympy.log.