Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question
    
SeriesCoefficient[] quickly yields a scaled version of the derivative; figuring out what the scale factor is is left as an exercise. –  J. M. Jun 11 '12 at 17:54
add comment

2 Answers 2

up vote 6 down vote accepted

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]
share|improve this answer
2  
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}. –  freddieknets Jun 11 '12 at 14:47
    
Yes this is what I mean. Thanks –  Faysal Aberkane Jun 11 '12 at 14:48
    
Ps Faysal, can you mark the answer as a solution? Thanks! –  freddieknets Sep 12 '12 at 9:37
add comment

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}]
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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