Is there a vectorized way to calculate gradient in sympy?

How to calculate the (symbolic) gradient of a multidimensional function in sympy?

Obviously, I could calculate separately the derivative for each variable, but is there a vectorized operation that does this?

for example

m=sympy.Matrix(sympy.symbols('abc d')) 

Now for i = 0..3 I can do:

 sympy.diff(np.sum(m*mT),m[i]) 

which will work, but I would rather do something like:

 sympy.diff(np.sum(m*mT),m) 

What does not work ("AttributeError: ImmutableMatrix does not have the _diff_wrt attribute").

+7
python sympy symbolic-math derivative
source share
2 answers

Just use list comprehension over m :

 [sympy.diff(sum(m*mT), i) for i in m] 

Also, do not use np.sum if you are not working with numeric values. The built-in sum better.

+6
source share

Here is an alternative to @asmeurer. I prefer this way because it returns a SymPy object instead of a Python list.

 def gradient(scalar_function, variables): matrix_scalar_function = Matrix([scalar_function]) return matrix_scalar_function.jacobian(variables) mf = sum(m*mT) gradient(mf, m) 
0
source share

All Articles