I am trying to use indexed functions in a For loop; to illustrate, I give a trivial example.
f[1, x_] := x^2
Now, I can define:
f[2,x_] := f[1,x]+x
f[3,x_] := f[2,x]+x
and the results are as expected, x^2 +x and x^2 + 2x, respectively. However, when I use the For loop
For[j = 1, j < 6, j++, f[j + 1, x] := f[j, x] + x]
I get the following error message:
$RecursionLimit::reclim2: Recursion depth of 1024 exceeded during evaluation of f[j,x].
What gives? (the real function I need to work with is a parametric integral, so the := definition is necessary).
thanks.
??f
to see thatSetDelayed
prevents the thej
inf[j, x] + x
from evaluation. $\endgroup$ – Henrik Schumacher Mar 18 at 16:40For
, I would just dof[1, x_] := x^2; f[n_ /; n > 1, x_] := f[n, x] = f[n - 1, x] + x
. $\endgroup$ – march Mar 18 at 16:41f[1, x_] := x^2; For[j=2, j<6, j++, f[j, x] := f[j-1, x] + x]
in a brand new fresh notebook with no prior calculations gives me no errors and seems to create the function definitions that you are looking for. Can you reproduce this? Does this method then work with your actual problem? If not then can you edit your post to show the actual problem so we can find a way to fix that too? $\endgroup$ – Bill Mar 18 at 17:31