Reputation: 9875
I want to know if it is possible in sympy
to take derivatives of polynomials and expressions using vector notation. For example, if I have an expression as a function of two coordinates, x1 and x2, can I just make one call to diff(x)
, where x
is a vector of x1
and x2
, or do I need to make two separate diff
calls to x1
and x2
, and stack them in a matrix?
This illustrates what works, versus what I want to work ideally:
import sympy
from sympy.matrices import Matrix
# I understand that this is possible:
x1 = sympy.symbol.symbols('x1')
x2 = sympy.symbol.symbols('x2')
expr_1 = x1**2+x2
poly_1 = sympy.poly(expr_1, x1, x2)
print Matrix([[poly_1.diff(x1)],[poly_1.diff(x2)]])
# but is something like this also possible?
x1 = sympy.symbol.symbols('x1')
x2 = sympy.symbol.symbols('x2')
x_vec = Matrix([[x1],[x2]])
expr_1 = x1**2+x2
poly_1 = sympy.poly(expr_1, x1, x2)
# taking derivative with respect to a vector
poly_1.diff(x_vec)
# should ideally return same as first example:
'''
Matrix([
[Poly(2*x1, x1, x2, domain='ZZ')],
[ Poly(1, x1, x2, domain='ZZ')]])
'''
# but it fails :(
Is there a way to take derivatives with respect to vectors in sympy
?
Thank you.
Upvotes: 5
Views: 3137
Reputation: 19093
Perhaps you are thinking of the jacobian
:
>>> Matrix([Poly(x**2+y,x,y)]).jacobian([x, y])
Matrix([[Poly(2*x, x, y, domain='ZZ'), Poly(1, x, y, domain='ZZ')]])
And that [x, y]
argument can be Matrix([x, y])
or its transpose, too.
Upvotes: 4