How do I store the results of NDsolve, in a table for plotting later?

Basically, I wanted to vary a parameter in my differential equations, while using NDsolve (ParametricNDsolve wasn't working for some reason, but that's for another question). I'm stuck looking for the correct command for the last part in the following code section (Very sorry for the crappy formatting).

For[e = 0, e < 6, e++, {Sol = NDSolve[{H[t] == -e*g[t], g == g[2*Pi],

g[Pi] == 1}, g[t], {t, 0, 2*Pi}]}; <Command to insert g[t]/.Sol in a Table>] My intention is to then plot all the solutions hence stored in the Table, using another loop, in a single graph. If this can be done directly, please provide some hints how.

• use Sol ={}; For[.e ==0, .., AppendTo[Sol,NDSolve[....]]? – kglr Jun 13 at 19:00
• You should take a look at ParametricNDSolve. That will make your life much easier. Also: forget For exists in Mathematica. Use Table or Do instead. – Sjoerd Smit Jun 13 at 19:12

In your code, Sol is replaced by the new solution in every iteration. If you have to use For, you can initialize sol to {} in the first argument of For and use AppendTo to append new solutions (below, I used g''[t] for your H[t]):

For[sol = {}; e = 0, e < 6, e++,
AppendTo[sol,
First@NDSolve[{g''[t] == -e*g[t], g == g[2*Pi], g[Pi] == 1},
g[t], {t, 0, 2*Pi}]]];
Plot[Evaluate[Flatten[g[t] /. sol]], {t, 0, 2 Pi},
PlotLegends -> ("e = " <> ToString[#] & /@ Range[0, 5])] Alternatively, you can use Table:

sol2 = Table[First@NDSolve[{g''[t] == -e*g[t], g == g[2*Pi], g[Pi] == 1},
g[t], {t, 0, 2*Pi}], {e, 0, 5}];
Plot[Evaluate[Flatten[g[t] /. sol2]], {t, 0, 2 Pi},
PlotLegends -> ("e = " <> ToString[#] & /@ Range[0, 5])]

same picture

A much better approach is to create a parametric solution using ParametricNDSolve or ParametricNDSolveValue (as suggested by Sjoerd in the comments):

pndsv = ParametricNDSolveValue[{g''[t] == -a*g[t], g == g[2*Pi], g[Pi] == 1},
g, {t, 0, 2*Pi}, {a}];
Plot[Evaluate[Table[pndsv[a][t], {a, 0, 5, 1}]], {t, 0, 2 Pi},
PlotRange -> All,  PlotLegends -> ("e = " <> ToString[#] & /@ Range[0, 5])]

same picture