How can I differentiate a function with respect to several variables, and evaluate it at the same time? I want to specify also the variable index that I want to differentiate, and the number of times I do it for each one.

  • $\begingroup$ SeriesCoefficient[] quickly yields a scaled version of the derivative; figuring out what the scale factor is is left as an exercise. $\endgroup$ Jun 11, 2012 at 17:54

2 Answers 2


Is this what you mean?

f[x_, y_] := Sin[x y^2]
Derivative[1, 0][f][x, y]

This is to get the derivative to x. To get, say, the second derivative to x and the first derivative to y, and evaluate in (0,Pi), you would write

Derivative[2, 1][f][0, Pi]
  • 2
    $\begingroup$ You could of course also use D, but it is a bit less compact: D[f[x, y], {x, 2}, y] /. {x -> 0, y -> Pi}. $\endgroup$ Jun 11, 2012 at 14:47
  • $\begingroup$ Yes this is what I mean. Thanks $\endgroup$
    – faysou
    Jun 11, 2012 at 14:48
  • $\begingroup$ Ps Faysal, can you mark the answer as a solution? Thanks! $\endgroup$ Sep 12, 2012 at 9:37

Here's a way a way that avoids the syntax a bit complicated of Derivative when a function has a lot of variables.

SetAttributes[MultiD, HoldFirst];
MultiD[f_[params__]] := f[params];
MultiD[f_[params__], diffVars__] :=
      diffList = ConstantArray[0, Length@{params}];
      MapThread[(diffList[[#1]] = #2) &, Transpose@{diffVars}];
      Derivative[##][f][params]& @@ diffList


f[x_, y_] := x^4 y^2;
MultiD[f[1, 2], {2, 1}, {1, 3}] 

A similar function can be done to get a derivative as a pure function. I wonder if there's a way to know the number of variables of a pure or interpolated function ?

RemoveHead[h_[args___]] := {args};
NKeys[symbol_] := RemoveHead @@@ DownValues[symbol][[All,1]];

(*For pure or interpolated functions NumberOfVariables needs to be given as option*)
PureD[f_,diffVars__List,OptionsPattern[]] :=
    Module[ {nVars,diffList},

        If[ (nVars = OptionValue["NumberOfVariables"])==Automatic,
            (*Gets the number of parameters of the last DownValue of f*)
            nVars = Length[NKeys[f][[-1]]];

        diffList = ConstantArray[0,nVars];
        MapThread[(diffList[[#1]] = #2)&,Transpose[{diffVars}]];

        Derivative[##][f]& @@ diffList


PureD[f, {2, 1}, {1, 3}]

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.