Main Content

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. Withcompile-time recursion, the code generator creates multiple versions of the recursive function in the generated code. These versions are known as function specializations. Withrun-time recursion, the code generator produces a recursive function. If compile-time recursion results in too many function specializations 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:

Treat the Input to the Recursive Function as a Nonconstant

Consider this function:

functiony = call_recfcn(n) A = ones(1,n); x = 5; y = recfcn(A,x);endfunctiony = recfcn(A,x)ifsize(A,2) == 1 || x == 1 y = A(1);elsey = A(1)+recfcn(A(2:end),x-1);endend

call_recfcncallsrecfcnwith the value 5 for the second argument.recfcncalls itself recursively untilxis 1. For eachrecfcncall, the input argumentx有不同的价值。代码生成器生成five specializations ofrecfcn, one for each call.After you generate code, you can see the specializations in the code generation report.

To force run-time recursion, incall_recfcn, in the call torecfcn, instruct the code generator to treat the value of the input argumentxas a nonconstant value by usingcoder.ignoreConst.

functiony = call_recfcn(n) A = ones(1,n); x = coder.ignoreConst(5); y = recfcn(A,x);endfunctiony = recfcn(A,x)ifsize(A,2) == 1 || x == 1 y = A(1);elsey = A(1)+recfcn(A(2:end),x-1);endend

After you generate code, in the code generation report., you see only one specialization.

Make the Input to the Recursive Function Variable-Size

Consider this code:

functionz = call_mysum(A)%#codegenz = mysum(A);endfunctiony = mysum(A) coder.inline('never');ifsize(A,2) == 1 y = A(1);elsey = A(1)+ mysum(A(2:end));endend

If the input tomysumis fixed-size, the code generator uses compile-time recursion. To force the code generator to use run-time conversion, make the input tomysumvariable-size by usingcoder.varsize.

functionz = call_mysum(A)%#codegenB = A; coder.varsize('B'); z = mysum(B);endfunctiony = mysum(A) coder.inline('never');ifsize(A,2) == 1 y = A(1);elsey = A(1)+ mysum(A(2:end));endend

Assign Output Variable Before the Recursive Call

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

functiony = callrecursive(n) x = 10; y = myrecursive(x,n);endfunctiony = myrecursive(x,n) coder.inline('never')ifx > 1 y = n + myrecursive(x-1,n-1);elsey = n;endend

To force the code generator to use run-time recursion, modifymyrecursiveso that the outputyis assigned before the recursive call. Place the assignmenty = nin theifblock and the recursive call in theelseblock.

functiony = callrecursive(n) x = 10; y = myrecursive(x,n);endfunctiony = myrecursive(x,n) coder.inline('never')ifx == 1 y = n;elsey = n + myrecursive(x-1,n-1);endend

See Also

Related Topics