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]]
Answer
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}}
Comments
Post a Comment