How to memoize a recursive function in Matlab?

2 views (last 30 days)
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 Comments
Mohammad Sami
Mohammad Sami on 21 May 2020
Perhaps increasing the cache size would help.
Christine Pepin
Christine Pepin on 21 May 2020
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?

Sign in to comment.

Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!