File Exchange

image thumbnail


version (1.45 KB) by Matthew Kelly
Computes the second-order finite difference approximation.

1 Download

Updated 30 Dec 2015

View Version History

View License

% dx = diffCenter(x,dt)
% Computes the second-order finite difference approximation of x with
% respect to t. A one-sided second order difference is used at the end
% points, so size(dx) == size(x).
% x = [m, n] = matrix of function values over a uniform time grid n
% dt = sampling period of x (default = 1)
% d = dx/dt = first derivative of x wrt t
% This command is very similar to Matlab's gradient command. The
% difference between the two is how they handle the boundaries.
% DiffCenter (this function) uses a second-order finite difference,
% while gradient (by Matlab) uses a first-order finite difference.
% The functions are identical for interior points.
% See also: cumInt, diff, gradient

Cite As

Matthew Kelly (2021). diffCenter (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (3)

Felipe G. Nievinski

"second-order" here is misleading, as it's still the first derivative.

Matthew Kelly

Neat! I wasn't aware of the gradient function. I read through the code for gradient, comparing it to diffCenter (my function).

The major difference between diffCenter and gradient is in how they handle the boundaries of the data. diffCenter uses a second-order (one-sided) finite difference, while gradient uses a first-order finite difference. Both use a second-order difference on interior points. As a result, the finite difference approximation used by gradient will have a spike in error at the boundaries.

That being said, gradient supports multi-dimensional derivatives and better error handling, while diffCenter does not.

In reading through diffCenter, I actually found an error: the coefficients in the boundary differences were off by a factor of 2, which is now fixed (version 2.0).

Duane Hanselman

The standard MATLAB function gradient already does this. So, I don't know how this would be useful.

MATLAB Release Compatibility
Created with R2012a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Inspired: diffCenterVar

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!