5
$\begingroup$

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?

$\endgroup$
3

2 Answers 2

5
$\begingroup$

You can do this:

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

D[sum, Indexed[x, 5]]
(* Piecewise[{{5, n >= 5}}, 0] *)
$\endgroup$
2
  • $\begingroup$ 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? $\endgroup$ Mar 18, 2020 at 21:09
  • 1
    $\begingroup$ @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. $\endgroup$
    – Szabolcs
    Mar 18, 2020 at 21:33
3
$\begingroup$

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] *)
$\endgroup$
1
  • $\begingroup$ In your code you specify the number of variables before taking the derivative. That's not exactly what I want. $\endgroup$ Mar 18, 2020 at 21:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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