Matlab gradient does not follow exact numerical formula

1 回表示 (過去 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.
  2 件のコメント
njj1
njj1 2017 年 8 月 24 日
Oh I see. Thanks!
awais munawar
awais munawar 2018 年 1 月 29 日
Good explanation

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by