Differentiating a Dot Product

I apologize if this type of question has been asked before, but a preliminary search turned up nothing.

I would like to differentiate dot products. For example, consider taking a derivative with respect to the $i$-th component of $P$ in the dot product $P \cdot X$. How do I teach Mathematica that is given by

$\frac{\partial (P\cdot X)}{\partial P_i} = \frac{\partial }{\partial P_i}(P_a X^a) = \delta^i_a X^a = X^i$

? Ideally, I would like to implement/generalize this rule to dot products of vectors in special relativity where the dot product is given by $a \cdot b = \eta_{\mu\nu} a^\mu b^\nu$. Thanks!

-

You don't really need to "teach" this to Mathematica, it knows how to take derivatives. For example, say you have arbitrary vectors xVec={x[1], x[2], ... x[n]} and pVec={p[1], p[2], ... p[n]}. Then you can take the derivative of the dot product with respect to one of the p[]'s straightforwardly using D:

n = 5;
xVec = Array[x, n];
pVec = Array[p, n];
D[xVec.pVec, p[3]]


which gives the expected answer x[3]. You can replace the standard dot product . with your own function.

More generally, (as nikie points out in the comments) you can take the derivative with respect to the complete vector pVec using

D[xVec.pVec, {pVec}]


which gives the expected answer {x[1], x[2], x[3], x[4], x[5]} (for n=5).

-
You can even write D[xVec.pVec, {pVec}] to get the gradient wrt pVec, or D[xVec.pVec, {pVec, 2}] to get the Hessian. It took me a long time to figure that out... –  nikie Feb 4 at 7:52