How to memoize a recursive function in Matlab?

2 次查看(过去 30 天)
I implemented a recursive function that computes the number of strings (or tosses) of length n with exactly k heads but no more than x of these occuring consecutively (this is for the biased coin tossing problem). For n>20, the execution time is very slow. I would like to reduce it using memoization, but am not sure how to use it correctly in a recursive function. This is my function and how I memoized it:
function C_coeff = NumStrings(n, k, x)
% Recursive function to compute the number of strings of length n with
% exactly k heads but no more than x of these occuring consecutively.
%
persistent memoizeNS;
if isempty(memoizeNS)
memoizeNS = memoize(@NumStrings);
end
vec = zeros(1, x+1);
if (k <= x)
C_coeff = nchoosek(n, k);
elseif (k == n && k > x)
C_coeff = 0;
elseif (x < k && k < n)
for j = 0:x
vec(j+1) = memoizeNS(n-1-j, k-j, x);
end
C_coeff = sum(vec);
else
return;
end
end
The function NumStrings(n,k,x) is called from a script and within a loop where k varies (n and x remain fixed). Therefore, a specific C_coeff may show up multiple times within the recursive function and I don't want to compute the same coefficient every time. Using this memoization technique doesn't change the execution time unfortunately. Any hint as to why? Thanks.
  2 个评论
Christine Pepin
Christine Pepin 2020-5-21
Thanks Mohammad. It does actually. That and clearing the cache. :)
How big can the cache size be? Is there a compromise between the cache size and the just running the function?

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

产品


版本

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by