I have quite a heavy function in MATLAB:
function [out] = f ( in1, in2, in3)
Which is called quite often with the same parameters. The function is deterministic so for given input parameters its output will always be the same.
What would be the simplest way of storing the results of computed inputs in the function such that if the function will be called again with the same output it would be able to answer quickly?
Is a persistent variable which maps (using containers.Map
or some other class) input set <in1, in2, in3>
to a result the way to go?
Note that any method which requires saving the data to disk is out of the question in my application.
MATLAB now ships with a function just for this purpose. The technique used is called "memoization" and the function's name is "memoize".
Check out : https://www.mathworks.com/help/matlab/ref/memoize.html
Persistent map is indeed a nice way to implement cached results. Advantages I can think of:
There is a file exchange submission, A multidimensional map class by David Young, comes with a function memoize() does exactly this. It's implementation uses a bit different mechanism (referenced local variable), but the idea is about the same. Compared with persistent map inside each function, this memoize() function allows existing function to be memoized without modification. And as pointed out by Oleg, using DataHash (or equivalent) can further reduce the memory usage.
PS: I have used the MapN class extensively and it is quite reliable. Actually I have submitted a bug report and the author fixed it promptly.
Below is an idea for a CacheableFunction class
Class definition
Testing it out...
And results