[Date Index]
[Thread Index]
[Author Index]
Re: Memory problem using NDSolve in For Loop
*To*: mathgroup at smc.vnet.net
*Subject*: [mg83363] Re: Memory problem using NDSolve in For Loop
*From*: Szabolcs Horvát <szhorvat at gmail.com>
*Date*: Sun, 18 Nov 2007 04:51:12 -0500 (EST)
*References*: <fhmhrn$atl$1@smc.vnet.net>
DBK wrote:
> I am running a number of simulations (sim) with different initial
> conditions (ic). The code I have written runs fine until I increase
> the number of simulations. In my "For" loop below, I thought that
> previous solutions (sol[sim]) were being cleared but this obviously is
> not happening. How do I clear sol and reduce my memory usage? Sorry if
> this is pretty basic stuff.
>
> For[sim = 1, sim < 2500, sim = sim + 1,
> sol[sim] =
> NDSolve[{equations, a[0] == 10, b[0] == .45, c[0] == .30,
> d[0] == .40, e[0] == ic[[sim, 1]], f[0] == ic[[sim, 2]]}, {a, b,
> c, d, e, f}, {t, 0, time}, MaxSteps -> Infinity,
> WorkingPrecision -> 5, MaxStepSize -> 0.10];
> AppendTo[outlist, {ic[[sim, 1]], ic[[sim, 2]], e[time] /. sol[sim],
> f[time] /. sol[sim]}]];
>
Never use For[] for simple looping in Mathematica. Use Do[] instead.
Instead of
For[sim = 1, sim < 2500, sim = sim + 1,
...]
use
Do[ ... , {sim, 1, 2499}]
or simply
Do[ ... , {sim, 2499}]
Whenever you need to collect the results into a list, use Table[]
instead of Do[].
This is a direct transformation of your program:
Table[
With[{sol =
NDSolve[{equations, a[0] == 10, b[0] == .45, c[0] == .30,
d[0] == .40, e[0] == ic[[sim, 1]], f[0] == ic[[sim, 2]]}, {a, b,
c, d, e, f}, {t, 0, time}, MaxSteps -> Infinity,
WorkingPrecision -> 5, MaxStepSize -> 0.10]},
{ic[[sim, 1]], ic[[sim, 2]], e[time] /. sol, f[time] /. sol}],
{sim, 2500}]
With[] is used to create local constants ('sol' in this case), but it
not strictly necessary here since you could just use
{ic[[sim, 1]], ic[[sim, 2]], e[time], f[time]} /. NDsolve[...]
instead of
sol = NDSolve[ ... ]
{ic[[sim, 1]], ic[[sim, 2]], e[time] /. sol, f[time] /. sol}
It can probably be made even more compact, but I cannot tell without
knowing the exact structure of 'ic'. You could try something like the
following (untested):
({#1, #2, e[time], f[time]} /.
NDSolve[{equations, a[0] == 10, b[0] == .45, c[0] == .30,
d[0] == .40, e[0] == #1, f[0] == #2}, {a, b, c, d, e, f}, {t, 0,
time}, MaxSteps -> Infinity, WorkingPrecision -> 5,
MaxStepSize -> 0.10]) & @@@ ic
Szabolcs
Prev by Date:
**Tally[ ] and Union[ ]**
Next by Date:
**NAntiDerivative function for using NDSolve to compute antiderivatives**
Previous by thread:
**Re: Memory problem using NDSolve in For Loop**
Next by thread:
**classes.m**
| |