Reputation: 7805
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?
Upvotes: 7
Views: 2609
Reputation: 91500
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
.
Upvotes: 8
Reputation: 10360
If you want an elementwise logarithm, and your matrices are all going to be single-column, you should just be able to use a list comprehension:
>>> m = sympy.Matrix(sympy.symbols('a b c d'))
>>> logm = sympy.Matrix([sympy.log(x) for x in m])
>>> logm
Matrix([
[log(a)],
[log(b)],
[log(c)],
[log(d)]])
This is kind of ugly, but you could wrap it in a function for ease, e.g.:
>>> def sp_log(m):
return sympy.Matrix([sympy.log(x) for x in m])
>>> sp_log(m)
Matrix([
[log(a)],
[log(b)],
[log(c)],
[log(d)]])
Upvotes: 1