Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to build a table where the iterator is based off of the ith-1 entry in the table.

In other words, the value at i is based on a function with i-1 as its input.

EXAMPLE: Let's assume we're trying to get a pressure profile for a static column of gas. Since a gas's density changes greatly with pressure changes, we would want to break the static column into, say, 50 sections. So, we set the pressure at the bottom of the column and calculate the pressure at the top of the section (i+1) using the formula $\ P_h = \rho g h/g_c$ (hydrostatic equation). The next section's known pressure is at i+1 and we'd solve for i+2.

I've tried For and Table and can't get it to work.

Thanks in advance.

Update: I've figured out how to do it with the For[] construct, but not without the loop.

pc = List[4100];
For[i = 1, i < 50, i++,
pc = Append[pc, pc[[i]] - \[Rho]gh/gc]]
share|improve this question
Sounds like an application for NestList or its relatives. However, before trying to come up with a specific example, I'd prefer to have a more concrete starting point. Can you provide an example of the function used for constructing the table? – Jens Jun 22 '12 at 21:30
Could you maybe talk about what you're actually trying to do so we could be more helpful? – J. M. Jun 22 '12 at 22:59
I'm having a hard time parsing your formula. We have MathJax available here for writing formulae like $P=P_0 \exp\left(-\frac{Mg}{RT}\right)$; you might wish to use it. You might also consider making the pressure dependence explicit... – J. M. Jun 23 '12 at 0:56
In that case, Verbeia's answer gives you what you want: NestList[# - \[Rho] g h/gc &, 4100, 50 - 1]. Though, I prefer 4100 - Range[0, 50 - 1] \[Rho] g h/gc myself. – J. M. Jun 23 '12 at 1:33
J.M.-- You're awesome. Both methods you show here work brilliantly and are twice as fast as that confounded For[] loop. – kale Jun 23 '12 at 1:42
up vote 6 down vote accepted

This is a pretty straightforward use of NestList

NestList[f, x, 3]

results in:

{x, f[x], f[f[x]], f[f[f[x]]]}

More complex manipulations use pure functions, for example:

NestList[f[#1, a] &, x, 3]

results in:

{x, f[x, a], f[f[x, a], a], f[f[f[x, a], a], a]}

If you have some other input you need to weave into the function, consider FoldList

FoldList[{First[#1] + 1, #2} &, {0, 0}, {a, b, c, d}]

which results in:

{{0, 0}, {1, a}, {2, b}, {3, c}, {4, d}}
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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