在 Python 中,我们有lru_cache
一个函数包装器。将其添加到您的函数中,该函数只会针对每个不同的输入参数计算一次。
示例(来自 Python 文档):
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
我想知道Matlab中是否存在类似的东西?目前我正在使用缓存文件,如下所示:
function result = fib(n):
% FIB example like the Python example. Don't implement it like that!
cachefile = ['fib_', n, '.mat'];
try
load(cachefile);
catch e
if n < 2
result = n;
else
result = fib(n-1) + fib(n-2);
end
save(cachefile, 'result');
end
end
我这样做的问题是,如果我改变我的功能,我需要删除缓存文件。
当我更改函数并且缓存已失效时,有没有办法通过 Matlab 实现这一点?