Cleanest way to cache function results in MATLAB

后端 未结 3 1459
轻奢々
轻奢々 2020-12-31 07:30

I have quite a heavy function in MATLAB:

function [out] = f ( in1, in2, in3)

Which is called quite often with the same parameters. The func

3条回答
  •  Happy的楠姐
    2020-12-31 08:21

    Persistent map is indeed a nice way to implement cached results. Advantages I can think of:

    • No need to implement hash function for every data type.
    • Matlab matrices are copy-on-write, which can offer certain memory efficiency.
    • If memory usage is an issue, one can control how many results to cache.

    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.

提交回复
热议问题