0

I want to use the code for computing Jacobian by sympy given in this answer.

But I want to give the variable and function lists as follows;

v_list=[x,y,z]
f_list=[f1,f2,f3]

However, the sympy commands there need v_list and f_list to be given as following;

v_list='x y z'
f_list=['f1','f2','f3']

Is there a way to write a python code that automatically convert v_list and f_list from the first shape that I gave to the shape suitable for the sympy command in that Jacobian function?

Masoud
  • 1,270
  • 7
  • 12
  • The is no reliable way to convert variable names to string in Python. On the other hand, the variable and function in the list need to be predefined, in other case, program throw `NameError`. That's why `sympy` gets them as string. – Masoud Jul 06 '19 at 22:04
  • @Masoud x, y, z are just three variable names. f1, f2 and f3 are three functions on these three variables defined beforehand. I use them without string mode since I will assign values to x, y and z and then ask some evaluations of f1, f2 and f3 which can't happen if I define them as string or symbols from the beginning. In fact I'm using them in another module without need of sympy, and now I just want to have a module to compute the Jacobian and return it back to the other module. So I need something automatically convert the first shape to the second shape mentioned in my question. – AmirHosein Sadeghimanesh Jul 07 '19 at 06:52
  • in python, functions has __name__ attribute, which is a string. But other object doesnt have such attribute and there is not a reliable way to convert name to string. one possible way is to define a new Class with name attribute and make x, y, z instances of that class. Anyway, I do not suppose the variables are generated dynamically in a metaprogramming form so that you need to convert them to string automatically and do magic. – Masoud Jul 07 '19 at 07:36

1 Answers1

1

The direct answer is

>>> sv_list = ' '.join([i.name for i in v_list])
>>> sf_list = [i.name for i in f_list]
>>> repr(sv_list)
'x y z'
>>> repr(sf_list)
['f1', 'f2', 'f3']

But a question is: why not use the built-in jacobian method of SymPy's Matrix?

>>> v_list = u1, u2 = symbols('u1:3')
>>> f_list = [2*u1 + 3*u2, 2*u1 - 3*u2]
>>> Matrix(f_list).jacobian(v_list)
Matrix([
[2,  3],
[2, -3]])

Note: the use of strings is not necessary; it is just a way to avoid creating variables.

smichr
  • 16,948
  • 2
  • 27
  • 34