Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting expression involving tranpose of vector to numerical function with lambdify

I have written a script in python that uses sympy to compute a couple of vector/matrix formulas. However, when I try to convert those to functions that I can evaluate with sympy.lambdify, I get a

SyntaxError : EOL while scanning string literal

Here's some code with the same error, so that you can see what I mean.

import sympy
x = sympy.MatrixSymbol('x',3,1)
f = sympy.lambdify(x, x.T*x)

So, the syntax error has to do with the expression "x'.dot(x)" and the conversion of ".T" to '.

How can I work around this to correctly define f from the above lambdify?

like image 704
Kostis Avatar asked Apr 19 '16 22:04

Kostis


2 Answers

Found a work around, although not the cleanest looking solution... but it works.

Use the implemented_function() method from sympy to define your function. Read full documentation here: http://docs.sympy.org/latest/modules/utilities/lambdify.html

Here is the code:

import sympy
import numpy as np
from sympy.utilities.lambdify import implemented_function


x = sympy.MatrixSymbol('x',3,1)

f = implemented_function(sympy.Function('f'), lambda x: x.T*x)

lam_f= sympy.lambdify(x, f(x))

Hope this solves your problem :)

like image 95
Hsad Avatar answered Sep 29 '22 16:09

Hsad


It has been solved in sympy version >= 1.1

Edit:

Example

when u define this x = sympy.MatrixSymbol('x',3,1) you are creating a matrix,

you can check its indexing and shape using print(sympy.Matrix(x))

Now that you want to multiply Transpose of x to x, you will have to give x a matrix of same shape that you have defined before

here try this:

from sympy import MatrixSymbol, lambdify, Matrix
x = MatrixSymbol('x', 3, 1)
f = lambdify(x, x.T*x)
a = Matrix([[1], [2], [3]])
print(f(a))

you can check this link out to understand lambdify better: http://docs.sympy.org/latest/modules/utilities/lambdify.html

like image 45
Tanay Agrawal Avatar answered Sep 29 '22 16:09

Tanay Agrawal