# Quickly differentiate and evaluate a function of several variables

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.

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

## 2 Answers

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]
• 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}. Jun 11, 2012 at 14:47
• Yes this is what I mean. Thanks Jun 11, 2012 at 14:48
• Ps Faysal, can you mark the answer as a solution? Thanks! 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__] :=
Module[{diffList},
diffList = ConstantArray[0, Length@{params}];
MapThread[(diffList[[#1]] = #2) &, Transpose@{diffVars}];
Derivative[##][f][params]& @@ diffList
];

Example

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*)
Options[PureD]={"NumberOfVariables"->Automatic};
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
];

Example

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