Matlab code to take time derivatives

I have a velocity command, which is:

$$v=k_1\rho cos(\alpha)$$

where each quantity $$\rho$$ and $$\alpha$$ depend by the time.

I would like now to take the time derivative of this, in order to use it as feedforward. The problem is that I have also an angular velocity command, which is much more complex than this, and do it by hand would be almost impossible to do it without mistakes.

So, my question is:

What is a matlab code that takes the time derivative of expression of this type?

In newer versions of Matlab (I can't remember when this change was made) you can define symbolic variables as a function of time, like

syms rho(t) alpha(t);

Symbolic constants are anything defined not as a function of time, like:

syms k1;

Then you can define your expression for v without needing to declare v itself as symbolic:

v = k1*rho*cos(alpha);

Finally, if you want the derivative of this, since you've defined $$\rho$$ and $$\alpha$$ as being time-dependent, just call the diff command:

dvdt = diff(v, t);

which yields the following result:

>> dvdt = diff(v, t)

dvdt(t) =

k1*cos(alpha(t))*diff(rho(t), t) - k1*sin(alpha(t))*rho(t)*diff(alpha(t), t)

You can clean it up by recognizing that diff(rho(t), t) is Matlab's way of expressing $$\dot{\rho}$$ and likewise for $$\alpha$$, so you wind up with

$$v = k_1 \rho \cos{\left(\alpha\right)} \\ \frac{d}{dt}v = k_1 \cos{\left(\alpha\right)}\dot{\rho} - k_1 \sin{\left(\alpha\right)} \rho \dot{\alpha}$$

• You may want to conclude that the final result for $\dot{v}$ is nothing but the outcome of applying the well-known chain rule for derivatives. Dec 13, 2020 at 22:37