Matlab gradient does not follow exact numerical formula

1 次查看(过去 30 天)
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?

采纳的回答

John D'Errico
John D'Errico 2017-8-24
编辑:John D'Errico 2017-8-24
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by