# How to estimate gradient of Jerk

A trajectory is described by a position vector, i.e., traj = $$[q_0, q_1,...,q_n]$$. The objective is to minimize the jerk of the trajectory.

I am referring to this code to understand how the gradient of jerk is defined. It's clear how Jerk is defined, but I am not clear how the gradient of jerk is defined. Any help to understand this much appreciated.

$$jerk_i = q_{i+3}-3q_{i+2}+3q_{i+1}-x_i, \forall jerk_i, i=1,...,n-3$$

In that implementation, $$\bigtriangledown jerk_i$$ is defined as follows:

$$\bigtriangledown jerk_i \; \mathrel{+}= -2 \cdot jerk_i , \quad \bigtriangledown jerk_{i+1} \; \mathrel{+}= 6 \cdot jerk_i, \quad \bigtriangledown jerk_{i+2} \; \mathrel{-}= 6 \cdot jerk_i, \quad \bigtriangledown jerk_{i+2} \; \mathrel{+}= 2 \cdot jerk_i$$

Not clear why they have defined gradient this way?

The code is computing the gradient of the cost, which is jerk squared, not the gradient of the jerk. The comment there is misleading! As written, it seems the code is implementing the chain rule of $$c = j^\top j$$ $$\frac{\partial c}{\partial q} = 2j\frac{\partial j}{\partial q}$$
$$2j$$ is set to temp_j and you can see how the partial of jerk w.r.t q is computed given the expression for jerk. The constants 1, -3, 3, and -1 can be read off.