# Define an $n$-variable function with $n$ undefined?

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?

• Sorry for code formatting instead of Latex, but I couldn't post it otherwise (it says that the post isn't properly formatted) Mar 18, 2020 at 19:52
• Mar 18, 2020 at 22:15
• Does f[x__]:=Total[{x}]; D[f[x1,t x2,x3],x2] work for you? Mar 19, 2020 at 19:07

You can do this:

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

D[sum, Indexed[x, 5]]
(* Piecewise[{{5, n >= 5}}, 0] *)

• 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? Mar 18, 2020 at 21:09
• @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. Mar 18, 2020 at 21:33

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] *)

• In your code you specify the number of variables before taking the derivative. That's not exactly what I want. Mar 18, 2020 at 21:07