MemoizedFunction
Call memoized function and cache results
Description
AMemoizedFunction
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 theFunction
property. However, theMemoizedFunction
object is not a function handle.
你第一次调用memoize的函数a certain set of input values, MATLAB®executes the function specified by theFunction
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.
TheMemoizedFunction
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
AMemoizedFunction
object is not aware of updates to the underlying function. If you modify the function associated with the memoized function, clear the cache with theclearCache
object function.
Creation
To create aMemoizedFunction
object, call thememoize
function.
The memoization of a function is associated with the input function and not with theMemoizedFunction
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.a = 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 forMemoizedFunction object |
stats |
Return cached values and statistics forMemoizedFunction object |