Numerical derivative of a vector

霸气de小男生 提交于 2019-12-01 07:47:18

问题


I have a problem with numerical derivative of a vector that is x: Nx1 with respect to another vector t (time) that is the same size of x. I do the following (x is chosen to be sine function as an example):

t=t0:ts:tf;
x=sin(t);
xd=diff(x)/ts;

but the answer xd is (N-1)x1 and I figured out that it does not compute derivative corresponding to the first element of x.

is there any other way to compute this derivative?


回答1:


You are looking for the numerical gradient I assume.

t0 = 0;
ts = pi/10;
tf = 2*pi;

t  = t0:ts:tf;
x  = sin(t);
dx = gradient(x)/ts

The purpose of this function is a different one (vector fields), but it offers what diff doesn't: input and output vector of equal length.


gradient calculates the central difference between data points. For an array, matrix, or vector with N values in each row, the ith value is defined by

The gradient at the end points, where i=1 and i=N, is calculated with a single-sided difference between the endpoint value and the next adjacent value within the row. If two or more outputs are specified, gradient also calculates central differences along other dimensions. Unlike the diff function, gradient returns an array with the same number of elements as the input.




回答2:


I know I'm a little late to the game here, but you can also get an approximation of the numerical derivative by taking the derivatives of the polynomial (cubic) splines that runs through your data:

function dy = splineDerivative(x,y)

% the spline has continuous first and second derivatives
pp = spline(x,y); % could also use pp = pchip(x,y);

[breaks,coefs,K,r,d] = unmkpp(pp);
% pre-allocate the coefficient vector
dCoeff = zeroes(K,r-1);

% Columns are ordered from highest to lowest power. Both spline and pchip
% return 4xn matrices, ordered from 3rd to zeroth power. (Thanks to the
% anonymous person who suggested this edit).
dCoeff(:, 1) = 3 * coefs(:, 1); % d(ax^3)/dx = 3ax^2;
dCoeff(:, 2) = 2 * coefs(:, 2); % d(ax^2)/dx = 2ax;
dCoeff(:, 3) = 1 * coefs(:, 3); % d(ax^1)/dx = a;

dpp = mkpp(breaks,dCoeff,d);

dy = ppval(dpp,x);

The spline polynomial is always guaranteed to have continuous first and second derivatives at each point. I haven not tested and compared this against using pchip instead of spline, but that might be another option as it too has continuous first derivatives (but not second derivatives) at every point.

The advantage of this is that there is no requirement that the step size be even.




回答3:


There are some options to work-around your issue.

First: you can make your domain larger. Instead of N, use N+1 gridpoints.

Second: depending on the end-point of interest, you can use

  1. Forward difference: F(x + dx) - F(x)
  2. Backward difference: F(x) - F(x - dx)


来源:https://stackoverflow.com/questions/25245365/numerical-derivative-of-a-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!