This link answers the question on how to express the derivative of a function with an arbitrary number of variables. However, what if I wanted the gradient? More specifically, if f[x1,...,xn] is a given function where n may vary, then how would I express its gradient? I could alway do a Do loop, but is there an easier way?

EDIT: More specifically, I would like a function F[f_,n_] that has f and the number of arguments n of function f as inputs. F[f_,n_] should output the gradient of f.

  • 1
    $\begingroup$ What about the function Grad[]? This seems to what you are looking for at first glance $\endgroup$ – Dunlop Oct 30 '19 at 6:54
  • $\begingroup$ @Dunlop That requires inputting the arguments, i.e., Grad[f[x1,...,xn],{x1,...,xn}], which isn't ideal in writing a function that takes in only a function f and the number of argument n. $\endgroup$ – Andrew Yuan Oct 30 '19 at 8:12
  • $\begingroup$ @Andrew Yuan Why do not you make a custom gradient, as for example, myGrad[expr_]:=Grad[expr,{x1,x2,...xn}]? $\endgroup$ – Alexei Boulbitch Oct 30 '19 at 8:53
ClearAll[f, F, n]
F[f_, n_] := Grad[f @ ##, {##}] & @@ Array[\[FormalX], n]


F[Times, 3]

{[FormalX][2] [FormalX][3], [FormalX][1] [FormalX][3], [FormalX][ 1] [FormalX][2]}

F[Sin[Total[{##}^2]] &, 2]

{2 [FormalX][1] Cos[[FormalX][1]^2 + [FormalX][2]^2], 2 [FormalX][2] Cos[[FormalX][1]^2 + [FormalX][2]^2]}

Alternatively, use the variable as an additional argument (instead of using \[FormalX]:

ClearAll[f, F2, n]
F2[f_, n_, var_: x] := Grad[f@##, {##}] & @@ Array[var, n]


F2[Times, 3]

{x[2] x[3], x[1] x[3], x[1] x[2]}

F2[Sin[Total[{##}^2]] &, 2, z]

{2 Cos[z[1]^2 + z[2]^2] z[1], 2 Cos[z[1]^2 + z[2]^2] z[2]}


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.