How do I store the return value of a function?
7 views (last 30 days)
Basically, my problem is resulted from translating my code from Mathematica to Matlab. In Mathematica, I define a function like this: foo[x_]:=foo[x]=something
It is a simple way to implement Memoization in Mathematica. The trick is that if you define a function as this, then when you for the first time call, say, foo, it will evaluate it. The next time you call foo, it will find that newly created definition of foo and use that in preference to the general rule. This means it will return the value without calculating foo a second time. Reference:( http://mathematica.stackexchange.com/questions/2639/what-does-the-construct-fx-fx-mean )
I want to find the counterpart function in Matlab, which avoid evaluating a function for a second time when call it later.
Basically, I have no idea about if there is a specifc function for it since I have checked the documentation and googled for a long time and still have no idea. Intuitively, I thought just assign it to an array may work. However, there are three crucial issues:
1.The index of array only takes value of integers, which is not general since my parameter could be non-integer or fraction.
2.If I use array structure, it could be risky. Because I may accidentally try to visit a unassigned value in the array which will return an undetermined value.
3.Because the array structure is consecutive in internal memory, which is a huge waste if just define foo(1) and foo(100) and leave other elements unassigned.
How can I store the return value of a function when it is evaluated first time?
Adam on 5 Dec 2016
Edited: Adam on 5 Dec 2016
can be used for caching of non-contiguous results with non-integer lookups. Whether it is worth the cost vs recalculating depends on the problem. Some things are so fast to calculate the simple recalculation is more efficient than storing in memory.
I have used a map like this once or twice to cache results of some calculation, though not often.
Jonathan A on 9 Oct 2019
I've been using cachedcall a lot and this is indeed very useful for simple workflows. For more complex workflows, I also built a class that encapsulates this functionnality and additionally provides a kind of dependency graph of functions. You can then request to compute the output of a specific function and all non-necessary functions won't be executed. The combination of this and cachedcall allows me to spare a lot of time in my scientific workflows. Hope this helps.