How to memoize a recursive function in Matlab?

조회 수: 2 (최근 30일)
Christine Pepin
Christine Pepin 2020년 5월 21일
댓글: Christine Pepin 2020년 5월 21일
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
Mohammad Sami
Mohammad Sami 2020년 5월 21일
Perhaps increasing the cache size would help.
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