Output Variable Must Be Assigned Before Run-Time Recursive Call - MATLAB & Simulink (original) (raw)
Main Content
Issue
You see this error message:
All outputs must be assigned before any run-time recursive call. Output 'y' is not assigned here.
Cause
Run-time recursion produces a recursive function in the generated code. The code generator is unable to use run-time recursion for a recursive function in your MATLABĀ® code because an output is not assigned before the first recursive call.
Solution
Rewrite the code so that it assigns the output before the recursive call.
Direct Recursion Example
In the following code, the statement y = A(1)
assigns a value to the output y
. This statement occurs after the recursive cally = A(1)+ mysum(A(2:end))
.
function z = call_mysum(A) B = A; coder.varsize('B'); z = mysum(B); end
function y = mysum(A) coder.inline('never'); if size(A,2) > 1 y = A(1)+ mysum(A(2:end));
else y = A(1); end end
Rewrite the code so that assignment y = A(1)
occurs in theif
block and the recursive call occurs in theelse
block.
function z = call_mysum(A) 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
Alternatively, before the if
block, add an assignment, for example, y = 0
.
function z = call_mysum(A) B = A; coder.varsize('B'); z = mysum(B); end
function y = mysum(A) coder.inline('never'); y = 0; if size(A,2) > 1 y = A(1)+ mysum(A(2:end));
else y = A(1); end end
Indirect Recursion Example
In the following code, rec1
calls rec2
before the assignment y = 0
.
function y = rec1(x) %#codegen
if x >= 0 y = rec2(x-1)+1; else y = 0; end end
function y = rec2(x) y = rec1(x-1)+2; end
Rewrite this code so that in rec1
, the assignment y = 0
occurs in the if
block and the recursive call occurs in the else
block.
function y = rec1(x) %#codegen
if x < 0 y = 0; else y = rec2(x-1)+1; end end
function y = rec2(x) y = rec1(x-1)+2; end