6

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?

Bitwise
  • 7,577
  • 6
  • 33
  • 50

2 Answers2

8

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.

asmeurer
  • 86,894
  • 26
  • 169
  • 240
  • Hey, just saw you are the lead developer of sympy - respect! Good job. It would be great if the matrix vectorization was more streamlined similar to Matlab symbolic toolbox. – Bitwise Jan 17 '14 at 01:39
  • Well, I didn't write most of the code, though. There have been a ton of contributors. – asmeurer Jan 17 '14 at 02:30
  • If you have any suggestion to make it better, let us know. – asmeurer Jan 17 '14 at 02:31
  • is there a way to pass in the base for log? – lingxiao Oct 06 '15 at 06:25
  • The base is given as a second argument to log, but for now, it just divides by `log(base)`, so `log(x, y)` just gives `log(x)/log(y)`. So in this case you could use `M.applyfunc(sympy.log)/sympy.log(base)`. – asmeurer Oct 07 '15 at 17:25
1

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)]])
senshin
  • 10,022
  • 7
  • 46
  • 59
  • Thanks - so no vectorized solution I guess. I hoped sympy would be a good replacement for Matlab symbolic stuff but I see sympy isn't there yet in terms of handling matrices. – Bitwise Jan 16 '14 at 19:37