I would like to supply a function as an argument to another function which then differentiates the function and evaluates it at a set of points.

Suppose I want to differentiate this function,

g[x1_, x2_] := x1^2 + x2^2

Doing the following doesn't work,

fDerivative[f_, z__] := Module[{grad = D[f[x], x]}, grad /. {x -> z}]

fDerivative[g, {1, 2}]


g`[{1, 2}]

Any ideas here?

I have also tried,

fDerivative1[f_, z__] := Module[{x, grad}, grad = ND[f[x], x, z]]

But this returns a much longer string of nonsense (to me, am sure that it makes sense to Mathematica!).



fDerivative[f_, z_] := Module[{x, v},
    v = Array[x, Length[z]];
    D[f @@ v, {v}] /. Thread[v -> z]

Your example:

g[x1_, x2_] := x1^2 + x2^2
fDerivative[g, {1, 2}]

{2, 4}

| improve this answer | |
  • $\begingroup$ Thank you! Much appreciated $\endgroup$ – ben18785 Nov 26 '18 at 17:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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