I wonder if it's possible to create a list with Table
from entries of the list itself. That is, as I'm creating the list, I append a new element as a function of previously added elements, in a "recursive" way.
For example, the following code does what I mean
lt = {1};
For[i = 2, i <= 5, i++, lt = Append[lt, lt[[i - 1]] + 1]];
lt
giving {1, 2, 3, 4, 5}
. I wonder if the same can be achieved with Table
. I naively tried
lt = {1};
lt = Table[lt[[i - 1]] + 1, {i, 2, 5}]
which unsurprisingly doesn't work. Maybe there is an alternative to this that avoids using For
and Append
. I've heard of RecurrenceTable
, but I'm not entirely sure how it works.
Any ideas?
NestList
, orNestWhileList
in case when you need access to more than one previous element. In your case, it would beNestList[# + 1 &, 1, 4]
. You can also use simpleNest
even when you need access to previous results, by collecting them in a (sub)list. Here is for example a way to compute Fibonacci numbers:NestList[{Last@ #, Total[#]} &, {1, 1}, 10][[All, 1]]
. Also,Nest
auto-compiles, so this method can be reasonably fast if the nesting function is compilable $\endgroup$