Matlab gradient does not follow exact numerical formula

4 views (last 30 days)
When the numerical gradient is computed, Matlab uses forward differences for the end points, and uses central differences for the interior points. However, when looking at the code, the central differences equation that they use does not divide by 2h. Here is their code:
% Take forward differences on left and right edges
if n > 1
g(:,1) = (f(:,2) - f(:,1))/(h(2)-h(1));
g(:,n) = (f(:,n) - f(:,n-1))/(h(end)-h(end-1));
end
% Take centered differences on interior points
if n > 2
h = h(3:n) - h(1:n-2);
g(:,2:n-1) = (f(:,3:n) - f(:,1:n-2)) ./ h;
end
The equation for central differences has a 2h in the denominator, i.e.,
f'(x) = (1/2h) * (f(x+h) - f(x-h)).
Why is Matlab not using this scaling factor?

Accepted Answer

John D'Errico
John D'Errico on 24 Aug 2017
Edited: John D'Errico on 24 Aug 2017
Actually, it DOES use the proper formula. The formula divides by delta. (I used delta here, because otherwise you have h in two places, used for two different purposes.)
delta = h(3:n) - h(1:n-2)
See that delta is computed as a difference that is twice the stride between consecutive points, at least if they are equally spaced.
If the points were not equally spaced, then the formula divides by an appropriate value, although it will no longer be second order as an approximation for the derivative.
Look carefully at the code. It is indeed correct.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!