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.

  • 1
    $\begingroup$ closely related: mathematica.stackexchange.com/q/102812/5478 $\endgroup$
    – Kuba
    Commented Jan 13, 2016 at 11:21
  • $\begingroup$ All you have to do is replace the := in your code with = and it should work $\endgroup$
    – Jason B.
    Commented Jan 13, 2016 at 11:26
  • $\begingroup$ It didnt even work by replacing := with =. $\endgroup$
    – Hippo
    Commented Jan 13, 2016 at 11:31
  • 1
    $\begingroup$ @SamridhiGambhir "didn't work" or "not getting the gradient" are vague statements which won't help you getting the answer fast. $\endgroup$
    – Kuba
    Commented Jan 13, 2016 at 11:34
  • $\begingroup$ @SamridhiGambhir Try Remove[ffd] before trying with =. $\endgroup$
    – Coolwater
    Commented Jan 13, 2016 at 11:36

2 Answers 2



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

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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.