# Gradient of interpolated 3D data in mathematica 9

tt = Flatten[Table[{x, y, z, btot[x, y, z]}, {x, -1, 1, 0.1}, {y, -1, 1,0.1}, {z, -1, 1, 0.1}], 2];
ff = Interpolation[tt]


Till here it is working fine as it is returning the values of the interpolated function at various {x,y,z} points.

Then I want to find the gradient of this interpolated function. But when I am using

ffd[x_,y_,z_]:= D[ff[x,y,z],{{x,y,z}}]


I am not getting the gradient.

• closely related: mathematica.stackexchange.com/q/102812/5478
– Kuba
Jan 13 '16 at 11:21
• All you have to do is replace the := in your code with = and it should work Jan 13 '16 at 11:26
• It didnt even work by replacing := with =. Jan 13 '16 at 11:31
– Kuba
Jan 13 '16 at 11:34
• @SamridhiGambhir Try Remove[ffd] before trying with =. Jan 13 '16 at 11:36

With

ffd[x_,y_,z_]:= D[ff[x,y,z],{{x,y,z}}]


the values of x, y, and z are substituted as arguments causing differentation wrt. numbers, i.e. nonsense. Moreover, you are using SetDelayed, which differentiate once for every call, which rather should be once for all time.

The solution to both problem is replacing SetDelayed with Set:

ffd[x_,y_,z_]= D[ff[x,y,z],{{x,y,z}}]


When you define your function like this, then e.g. ffd[.5, .5, .5] is really D[ff[.5, .5, .5], {{.5, .5, .5}}].

to avoid scoping issues with

x=5;
ffd[x_, y_, z_] = D[ff[x, y, z], {{x, y, z}}]


you can use

ffd = Evaluate[D[ff[#, #2, #3], {{#, #2, #3}}]] &


& means there is a held Function so we have to use Evaluate to force computation of gradien so it is not repeated each time.