Calculate the derivative of a vector

浪子不回头ぞ 提交于 2019-11-27 09:38:26

Here are three ways you can accomplish this. The first uses subs, the second uses a symfun, and the third uses complex step differentiation:

% 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 for performing first- and second-order complex step differentiation on my GitHub: cdiff. Note that complex step differentiation won't work well for higher order derivatives. It's best when one only has a non-differentiable function or needs fast numerical first derivatives.

For the sake of completeness, 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 of gradient is defined by a spacing vector instead of a scalar. (time or angle vector is appropriate) - in this case it is obviously necessary to split up the dimensions. (Though I don't know why.)

So alternatively, though not necessary:

dX = gradient(Phi(1,:),t);
dY = gradient(Phi(2,:),t);
dZ = gradient(Phi(3,:),t);
dPhi = [dX; dY; dZ];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!