MemoizedFunction
Call memoized function and cache results
Description
A MemoizedFunction
object maintains the memoization
semantics of a function handle and a cache of the function call results. It has the same
calling syntax as the function handle specified in the Function
property. However, the MemoizedFunction
object is not a function
handle.
The first time you call the memoized function with a certain set of input values,
MATLAB® executes the function specified by the Function
property and caches the results. In later calls to the memoized function with the same
set of inputs, MATLAB returns the cached results instead of executing the function again.
The MemoizedFunction
object maintains the
cache of inputs and the corresponding outputs. When it is invoked, MATLAB returns
the associated cached output values if the following conditions are
true.
The input arguments are numerically equal to cached inputs. When comparing input values, MATLAB treats
NaN
s as equal.The number of requested output arguments matches the number of cached outputs associated with the inputs.
Caution
A MemoizedFunction
object is not aware of
updates to the underlying function. If you modify the function associated
with the memoized function, clear the cache with the clearCache
object function.
Creation
To create a MemoizedFunction
object, call the memoize
function.
The memoization of a function is associated with the input function
and not with the MemoizedFunction
object. Therefore,
keep the following in mind.
Constructing a new
MemoizedFunction
object to the same function creates another reference to the same data. Two variables that memoize the same function share a cache and object property values, such as cache size. In the following example, the variablesa
andb
share a cache and have the same value for cache size.Similarly, clearing the cache fora = memoize(@svd); b = memoize(@svd);
b
(b.clearCache
) also clears the cache fora
, and any other variables that memoize thesvd
function.clearCache
is aMemoizedFunction
object function.Assigning a
MemoizedFunction
object to a new variable creates another reference to the same data. In the following example, the variablesc
andd
share data.c = memoize(@svd); d = c;
Clearing a variable does not clear the cache associated with the input function. To clear the cache for a
MemoizedFunction
object that no longer exists in the workspace, create a newMemoizedFunction
object to the same function, and use theclearCache
function on the new object. Alternatively, you can clear caches for allMemoizedFunction
objects using theclearAllMemoizedCaches
function.
Properties
Object Functions
clearCache | Clear cache for MemoizedFunction object |
stats | Return cached values and statistics for MemoizedFunction
object |
Examples
Version History
Introduced in R2017a