5

I would like to define an $n$-variable function with $n$ undefined. For example, I want something like this:

$$ f(x_1, \, \dots, \, x_n) = x_1 + \dots + x_n $$

And afterwards I want to take its derivatives with respect to x_j like this

$$ \dfrac{\partial}{\partial x_j} f = 1 $$

Is it possible to realise in Mathematica?

David G. Stork
  • 41,180
  • 3
  • 34
  • 96
  • Sorry for code formatting instead of Latex, but I couldn't post it otherwise (it says that the post isn't properly formatted) – Anatoliy Lotkov Mar 18 '20 at 19:52
  • Similar questions: https://mathematica.stackexchange.com/questions/188270/derivative-of-a-function-in-undefined-dimension, https://mathematica.stackexchange.com/questions/208664/n-derivatives-on-a-function-of-n-variables – Michael E2 Mar 18 '20 at 22:15
  • Does f[x__]:=Total[{x}]; D[f[x1,t x2,x3],x2] work for you? – Somos Mar 19 '20 at 19:07

2 Answers2

5

You can do this:

sum = Sum[i*Indexed[x, i], {i, 1, n}]

D[sum, Indexed[x, 5]]
(* Piecewise[{{5, n >= 5}}, 0] *)
Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
  • Yes, that's what I wanted. Thank you. But somehow it stops working in slightly more difficult example: p = Product[Indexed[x, i] - Indexed[x, j], {j, 1, N}, {i, 1, j - 1}]; D[p, Indexed[x,5]] returns zero. Could you explain where the problem is? – Anatoliy Lotkov Mar 18 '20 at 21:09
  • 1
    @HomoUniversalis I wish I could answer that but I can't. I was actually surprised that it worked with Sum—it must be a special feature of Sum. As far as I know, Mathematica can't really do such calculations, where the number of variables is not fixed. – Szabolcs Mar 18 '20 at 21:33
3

If you have your function take in a list, so you can deal with arbitrary length inputs...

ff[lst_?ListQ] := Total@lst

Then you can do

xs = Array[x, 5]
(* {x[1], x[2], x[3], x[4], x[5]} *)

D[ff[xs], x[4]]
(* 1 *)

D[ff[xs], x[40]]
(* 0 *)

Slightly more complicated

gg[lst_?ListQ] := Times @@ lst

D[gg[xs], x[1]]
(* x[2] x[3] x[4] x[5] *)
MikeY
  • 7,153
  • 18
  • 27