Wolfram Function Repository
Instant-use add-on functions for the Wolfram Language
Function Repository Resource:
Evaluate an expression while temporarily caching results from specified functions
ResourceFunction["WithCachedValues"][{f1,f2,…},expr] evaluates expr while temporarily caching values returned by functions fi. |
Define a function that doesn't evaluate quickly:
In[1]:= |
WithCachedValues can evaluate expressions while automatically remembering function values for f so they only have to be computed once:
In[2]:= |
Out[2]= |
The function values are only remembered within WithCachedValues and will be cleared after it finishes:
In[3]:= |
Out[3]= |
In[4]:= |
Out[4]= |
When fitting a numerical solution to a differential equation, you may want to cache the solution to reduce the number of calls to NDSolveValue because NonlinearModelFit will call the model many times:
In[5]:= |
Out[9]= |
Memoization can be used for the model (as is discussed in the documentation of NonlinearModelFit), but it is unlikely that the cached solutions are of much use after the fit has completed. Instead, cache the NDSolveValue results during the fitting process without storing them permanently:
In[10]:= |
Out[12]= |
Plot the solution:
In[13]:= |
Out[13]= |
All assignments made to cached functions inside of WithCachedValues will be lost afterwards:
In[14]:= |
Out[15]= |
In[16]:= |
Out[16]= |
This work is licensed under a Creative Commons Attribution 4.0 International License