Adding values in memoize function

2 views (last 30 days)
mumin chy
mumin chy on 3 May 2019
Answered: Samayochita on 23 Apr 2025
Hey
I am using memoize function for memorizing some values of a function that is computationally very expensive. It will help me to avoid repeating evaluation for same inputs again.
My question is: I can know some other values of the function f(x) (f1, f2, f3) for few inputs x= x1, x2, x3 after I compute the first computation of the function f(x) with x=x=x0. I don't have to compute them but I will only get those information after first computation with any other values. So I dont want to recompute those function again as I know them from system behavious. Is there a way to insert those into memoize function so that my function will memorize them and will not recompute them.
I was trying to modify memoizedFcn.stats.Cache.Inputs and memoizedFcn.stats.Cache.Outputs to insert them. But I was not successful.
Thanks in advance

Answers (1)

Samayochita
Samayochita on 23 Apr 2025
Hi mumin chy,
I understand that the goal is to inject known input-output pairs into the cache of a memoized function, so that when the function is called later with those inputs, the memoized function can return the known results without recomputing them.
However, the “memorize” function does not provide a way to directly modify the internal cache (memoizedFcn.stats.Cache.Inputs and memoizedFcn.stats.Cache.Outputs). These are read-only statistics and not meant to be manipulated for actual cache injection.
The workaround is to trick memoize into thinking it computed values like f(x1) without actually running the expensive function. Wrap f(x) in a function that:
  • First checks if a known value for x exists (in containers.Map)
  • If yes → return that known value (without calling f(x))
  • If no → compute f(x) and let “memorize” store it normally
This ensures that computation of f(x1) or f(x2) will not happen again, and they are returned from the known values.
For more information on the MATLAB functions used above, please refer to the following documentation links:

Categories

Find more on Function Creation in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!