# Find partial derivatives when the number of variables is unknown

The idea is that I have a defined function of $n$ variables. I want to find out $n$ and get partial derivation for each of variables,

Suppose you have a function

f[w_,x_,y_,z_]: = w^2+x^2+y^2+z^2


Is it possible to find partial derivation using - say - 3rd variable (in this case $y$), that is

$\frac{df}{dy} = 2 y$?

-
f[w_, x_, y_, z_] := w^2 + x^2 + y^2 + z^2;D[f[w, x, y, z], y] – tchronis Jan 27 '14 at 15:11
@Kuba That's a general idea, but names of the variables and their number is not the same each time. – Pygmalion Jan 27 '14 at 15:19
Well, if it is a general idea - elaborate more ! Put this way the question is easy enough to answer after browsing the documentation for 5 minutes. – Sektor Jan 27 '14 at 15:42
@Pygmalion The names in case of Derivative are not responsible for anything, first part [0,0,1,0] is. – Kuba Jan 27 '14 at 16:12
@Kuba OK, but this just transformed one problem to another one. For i=3 I have to create "Derivative[0,0,1,0][f][x1,x2,x3,x4]" – Pygmalion Jan 27 '14 at 16:36

## 2 Answers

Answering your comment:

idea is that I have a defined function of n variables. I want to find out n and get partial derivation for each of variables, i=1...n

I'm sure there must be easier ways to know how many patterns are used to define the function. Also, please consider the following solution as partial, since it doesn't account for example for UpValues or multiple definitions.

Anyway:

f[w_, x_, y_, z_] := w + x^2 + y^3 + z^4
vars = Length@ Flatten[ReleaseHold[(DownValues@f)[[1, 1]] /.
HoldPattern[a__] :> Hold@Verbatim[a] /.
HoldPattern -> Sequence /. f -> List] /. Verbatim -> List];
derivs = Derivative[Sequence @@ #][f] & /@ IdentityMatrix[vars];
derivs[[4]][1, 2, 3, 4]
(*
256
*)

-
+1. What if f = ArcTan? – Silvia Jan 27 '14 at 19:21
+1 derivs[[3]] returns 3 #3^2 & which is generally speaking what I am looking for. However, would it be possible to change derivs in order to return 3 y^2? – Pygmalion Jan 29 '14 at 15:58
@Pygmalion Something like derivs = Derivative[Sequence @@ #][f][w, x, y, z] & /@ IdentityMatrix[vars] ? – Dr. belisarius Jan 29 '14 at 16:12
Kind of. Maybe I am too demanding, but my idea was to create Mathematica procedure that finds all partial derivatives of an arbitrary function not knowing either number of variables or their names. In your solution you have to know that names of variables (w,x,y,z). Quite possibly my problem is unsolvable within Mathamatica – Pygmalion Jan 29 '14 at 16:21
@Pygmalion The problem is that those aren't "names" but patterns – Dr. belisarius Jan 29 '14 at 16:26

If the function is a polynomial, you can use

fd[expr_] := D[expr, #] & /@ Variables[expr]


Test:

fd[w^2 + x^2 + y^2 + z^2]

Out[] = {2 w, 2 x, 2 y, 2 z}


Or a slightly longer version with better looking output:

fd[expr_] := (With[{x = #}, HoldForm[D[expr, x]]] -> D[expr, #]) & /@ Variables[expr]

fd[w^2 + x^2 + y^2 + z^2]

-