Why gradient and diff give different results

34 views (last 30 days)
Ki on 8 Feb 2016
Answered: the cyclist on 8 Feb 2016
Hi there, I am trying to derive a force from given potential, that F = - gradient of potential if mass is one. To test it, I try to set up a very simple 2D case with potential is
A=[1 2 3; 3 2 6; -2 -7 2];
[fx, fy]=gradient(A, dx, dy);
Now I am thinking to use diff instead. ax=diff(A')/dx; ay=diff(A)/dy;
Ignore the fact that diff will lose 1 row or column, the numbers of results for those two methods are not in agreement as well. So why is that? Besides differentiation, what else gradient calculate?

Accepted Answer

the cyclist
the cyclist on 8 Feb 2016
The exact algorithm that gradient uses is given at the bottom of the documentation page for gradient.
It uses the central difference (two-sided difference, divided by 2) for central points, and single-side difference at the edges.

More Answers (0)


Community Treasure Hunt

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

Start Hunting!