Calculate the derivative of a vector
I have the following function (Viviani curve):
Phi = @(t)[ cos(t)^2, cos(t)*sin(t), sin(t) ]
Just check that it is valid:
s = linspace(0,T,1000);
plot3(cos(s).^2, cos(s).*sin(s), sin(s));
How do I get a function Phi
(possibly multiple times) that represents the Viviani curve at the point t
where t
from 0
to goes 2*pi
? Have I identified a Phi
suitable one for such a derivative? I tried diff
it but it didn't save Phi
as I needed it.
If the second derivative is going to be Phi_d2
, I need to get its value (for example, in t = 0
).
How can I achieve this?
source to share
Here are three ways to accomplish this. The first uses subs
, the second uses symfun
, and the third uses a complex differentiation of steps :
% Using subs
syms t
Phi = [cos(t) cos(t).*sin(t) sin(t)];
Phi_d2 = diff(Phi,t)
double(subs(Phi_d2,t,0))
% Using symfun
syms t
Phi(t) = [cos(t) cos(t).*sin(t) sin(t)];
Phi_d2 = diff(Phi,t)
double(Phi_d2(0))
% Using complex step differentiation
Phi = @(t)[cos(t) cos(t).*sin(t) sin(t)];
h = 2^-28;
cdiff = @(f,x)imag(f(x(:)+1i*h))/h;
Phi_d2 = cdiff(Phi,0)
You can find a function to perform a complex differentiation steps of the first and second order on my GitHub:cdiff
. Note that complex step differentiation will not work well for higher order derivatives. It is best when one has a non-differentiable function or fast numerical first derivatives are needed.
source to share
For completeness of the numerical solution without using any additional toolboxes:
N = 999;
t = linspace(0,2*pi,N+1);
Phi = [cos(t); cos(t).*sin(t); sin(t)];
dPhi = gradient(Phi,2*pi/N)
For non-uniformly spaced argument vectors, the second parameter gradient
is determined by the distance vector instead of the scalar. (suitable vector of time or angle) - in this case, obviously, the dimensions need to be divided. (Although I don't know why.)
So alternatively, although not needed:
dX = gradient(Phi(1,:),t);
dY = gradient(Phi(2,:),t);
dZ = gradient(Phi(3,:),t);
dPhi = [dX; dY; dZ];
source to share