1
$\begingroup$

When I enter the following:

Clear["Global`*"]
Func[f_, xx_] := Sum[D[f, xx[[s]]], {s, 1, 2}]
Func[x^2 + y^2, {x, y}]
Func[x^2 + s^2, {x, s}]

The first function evaluation works fine. The second gives the error "General: 2 is not a variable". The following expression appears in the stack trace, which makes it pretty clear why this happens:

$$ \sum_{s=1}^2 \partial_{(x,s)[[s]]} (s^2 + x^2) $$

The input variable $s$ is colliding with the sum index $s$.

It's pretty clear that I could avoid this by either

  1. Using very obscure index names so I'm unlikely to ever use then when calling the function later.
  2. Use normal index names but then take care to avoid using these as variables later on.

Neither of these seems ideal. Is there any way to "isolate" the sum index so that it won't collide with the input variables?

$\endgroup$
3
  • 3
    $\begingroup$ You could scope s using Module. Func[f_, xx_] := Module[{s}, Sum[D[f, xx[[s]]], {s, 1, 2}]] $\endgroup$ Nov 20, 2019 at 22:59
  • 1
    $\begingroup$ Discussion about the need to localize the variables in Table and Sum can be found in Do Table iteration variables need to be localized using Module?. $\endgroup$
    – WReach
    Nov 20, 2019 at 23:21
  • $\begingroup$ Thank you both! This solved my problem $\endgroup$
    – meldefon
    Nov 21, 2019 at 19:47

1 Answer 1

2
$\begingroup$

As a workaround, you can just use

Func[f_, xx_] := Total@Grad[f, xx]
Func[x^2 + y^2, {x, y}]
Func[x^2 + s^2, {x, s}]

2 x + 2 y

2 s + 2 x

$\endgroup$
1
  • $\begingroup$ Thanks for the suggestion, but computing the gradient was just an example - I was hoping for a generally applicable solution. $\endgroup$
    – meldefon
    Nov 21, 2019 at 19:47

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.