# Storing values of NDSolve or NIntegrate

I am looking in plotting some solutions of NDSolve or NIntegrate but they take too much time to run, thus it is not handy if I have to adjust some legend and thus run them multiple times. Is there a way to solve them once and store them in a table? If yes, how?

Yes, there indeed is. I'd suggest generating your solutions as a table which you could, e.g., export. As an example - which you haven't given so I'm guessing here - assume that your function looks like

f[a_]:=NIntegrate[g[x,a],{x,x0,x1}];


which you want to plot for different a but evaluation of the integral over g[x,a] takes very long. Generate a table of pairs like so and export it or plot is

pairs=ParallelTable[{a,f[a]},{a,a0,a1,da}];
ListPlot[pairs]
Export["path/you/like/pairs.dat",pairs];


NDSolve returns InterpolatingFunction objects. If you can see these in the notebook, they will be saved together with the notebook.

Consider the following:

The first InterpolatingFunction was returned by running NDSolveValue. I then copied it to an input cell as well, just for demonstration. Now, if I save this notebook, close Mathematica, and then open the notebook again, I will find that f still works after I have evaluated the assignment. Similarly, I can copy the output cell to an input cell (just like I did in the screenshot above) and it too will work. What we have learned from this: InterpolatingFunction objects are stored with the notebook, they persist between Mathematica sessions.

As of 11.3 there is a similar way to store lots of different data types.

This works by right-clicking the InterpolatingFunction and clicking Iconize. The InterpolatingFunction will then turn into an Iconize expression:

This works in the same way. It stores the object in the notebook, so when you open the notebook the next time you can load all of the data from it.

We have seen that InterpolatingFunction already does this, but Iconize is worth mentioning because it is even more general. You can do it on any kind of notebook expression.

Finally, it is worth noting that the values that the interpolation works with are accessible with the Grid and ValuesOnGrid properties:

You can save the values to file and then recreate the interpolation later using Interpolation. Here's an example:

interp = NDSolveValue[{y'[x] == y[x] Cos[x + y[x]], y[0] == 1}, y, {x, 0, 30}];
grid = interp["Grid"];
values = interp["ValuesOnGrid"];
Interpolation[Transpose[{grid, values}]]