I'm trying to create a certain "excel-like" recursive function, which runs through a pre-defined list and performs an operation dependent upon the current position (similar to the "drag down" type functionality of Excel). Here is some example code, where "m" is the list:
alt[x_] := If[Mod[x, 4] == 3 || Mod[x, 4] == 1, 0, If[Mod[x, 4] == 2, 1, -1]]
ex[x_] := ex[x] = ex[x - 1] + alt[x]*m[[x]]
ex[1] = 0
(* 0 *)
$RecursionLimit = Infinity
(* ∞ *)
ex[10000]
However when evaluating at a large point, the program quits the calculation without an error. Thanks so much for any advice!
Answer
Your example illustrates what you're looking for fairly nicely. One thing I might recommend in the future is sample code for generating m
such as:
SeedRandom[1234];
m = RandomInteger[{-100, 100}, 10000];
This produces a random set of integers between -100 and 100 that anyone with Mathematica can reproduce for themselves.
[With your example, I think the problem is that the recursive function takes up too much memory. Unfortunately, the Mathematica front-end is still 32-bit (although I believe that will change in the next few months with the release of MMA 12).] EDIT: As b3m2a1 pointed out, this reason is not correct, however the following should still work:
mylist = Table[ex[i], {i, 10000}]
Due to the memoization you have defined in your function, once ex[2]
is called, MMA now knows the value of ex[2]
so that on the subsequent call of ex[3]
it does not have to do any recursion but instead calls ex[2] + alt[3]*m[[3]]
which evaluates to 6 + 0 * -93
, rather than ex[2] + 0 * -93
. With the Table
each step of ex[i]
is stored before ex[i + 1]
is called.
Comments
Post a Comment