Matlab gradient does not follow exact numerical formula

조회 수: 7 (최근 30일)
njj1
njj1 2017년 8월 24일
댓글: awais munawar 2018년 1월 29일
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에서 Mathematics에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by