Numerical derivative of a vector

I have a problem with the numeric derivative of a vector x: Nx1 relative to another vector t (time) equal to size x. I do the following (taking a sine function as an example):

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

      

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

is there any other way to calculate this derivative?

+3


source to share


3 answers


Are you looking for digital I guess. gradient

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 different (vector fields), but it offers what it diff

doesn't: an 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 i-th value being specified

enter image description here

The gradient at the endpoints, where i = 1 and i = N, is calculated with the one-sided difference between the endpoint value and the next adjacent value within the string. If two or more outputs are specified, the Gradient also calculates center differences from other dimensions. Unlike the diff function, gradient returns an array with the same number of elements as input.

+8


source


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 polynomial (cubic) splines that go 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);

      



A polynomial is spline

always guaranteed to have continuous first and second derivatives at every point. I have not tested or compared this using pchip

instead spline

, but it might be a different option as it also has continuous first derivatives (but not minor derivatives) at every point.

This has the advantage that there is no requirement for the step size to be even.

+2


source


There are several solutions to your problem.

First: you can grow your domain. Instead N

, use N+1

gridpoints.

Second: depending on the endpoint, you can use

  • Moving forward: F(x + dx) - F(x)

  • Difference: F(x) - F(x - dx)

0


source







All Articles