在 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 实现这一点,当我更改函数并且缓存已失效时?
最佳答案
自 matlab 2017 起可用: https://nl.mathworks.com/help/matlab/ref/memoizedfunction.html
a = memoized(@sin)
关于matlab - Matlab中是否存在函数缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21480673/