Force Code Generator to Use Run-Time Recursion

When your MATLAB® code includes recursive function calls, the code generator uses compile-time or run-time recursion. With compile-time recursion, the code generator creates multiple copies of the function in the generated code. With run-time recursion, the code generator produces a recursive function. If compile-time recursion results in too many function copies or if you prefer run-time recursion, you can try to force the code generator to use run-time recursion. Try one of these approaches:

Make the Input to the Recursive Function Variable-Size

Consider this code:

function z = call_mysum(A)
%#codegen
z = mysum(A);
end

function y = mysum(A)
coder.inline('never');
if size(A,2) == 1
    y = A(1);
else
    y = A(1)+ mysum(A(2:end));
end
end

If the input to mysum is fixed-size, the code generator uses compile-time recursion. To force the code generator to use run-time conversion, make the input to mysum variable-size by using coder.varsize.

function z = call_mysum(A)
%#codegen
B = A;
coder.varsize('B');
z = mysum(B);
end

function y = mysum(A)
coder.inline('never');
if size(A,2) == 1
    y = A(1);
else
    y = A(1)+ mysum(A(2:end));
end
end

Assign Output Variable Before the Recursive Call

The code generator uses compile-time recursion for this code:

function y = callrecursive(n)
x = 10;
y = myrecursive(x,n);
end

function y = myrecursive(x,n)
coder.inline('never')
if x > 1
    y = n + myrecursive(x-1,n-1);
    
else
    y = n;
end
end

To force the code generator to use run-time recursion, modify myrecursive so that the output y is assigned before the recursive call. Place the assignment y = n in the if block and the recursive call in the else block.

function y = callrecursive(n)
x = 10;
y = myrecursive(x,n);
end

function y = myrecursive(x,n)
coder.inline('never')
if x == 1
    y = n;  
else
    y = n + myrecursive(x-1,n-1);
end
end

More About

Was this topic helpful?