Resolve Error: Output Variable Must Be Assigned Before Run-Time Recursive Call
R2026bIssue
When the code generator cannot determine recursion depth, it generates code that performs the recursive calls at run time. This is called run-time recursion. To use run-time recursion, the MATLAB® code must assign a value to the output variable before the first recursive call. Otherwise, the code generator produces this error:
All
outputs must be assigned before any run-time
recursive call. Output 'output_variable' is not assigned
here.
Possible Solutions
To resolve this error, rewrite your code so that it assigns a value to the output variable before the recursive call. This solution can be applied whether the function uses direct or indirect recursion.
Direct Recursion
A directly recursive function calls itself. For example, this function calls
itself in the if statement and assigns a value to the output
variable out in the else statement. If the
input array A is variable size, code generation fails because the
code generator must use run-time recursion and the function assigns a value to
out after the recursive call.
function out = directRecur_error(A) if numel(A)>1 out = A(1)+directRecur_error(A(2:end)); else out = A(1); end end
To resolve this error, rewrite the code so that assignment to the output variable
occurs before the recursive call. In this example, assign a value to
out in the if block and perform the
recursive call in the else block.
function out = directRecur_example1(A) if numel(A)==1 out = A(1); else out = A(1)+directRecur_example1(A(2:end)); end end
Alternatively, assign a dummy value to out before the
if block.
function out = directRecur_example2(A) out = 0; if numel(A)>1 out = A(1)+directRecur_example2(A(2:end)); else out = A(1); end end
Indirect Recursion
An indirectly recursive function calls itself through one or more other functions.
For example, this function, indirectRecurA_error, calls
indirectRecurB, which then calls
indirectRecurA_error. Code generation fails because the code
generator must use run-time recursion and the function assigns a value to
out after the recursive call.
function out = indirectRecurA_error(x) if x>=0 out = indirectRecurB(x-1)+1; else out = 0; end end function out = indirectRecurB(x) out = indirectRecurA_error(x-1)+2; end
To resolve this error, rewrite the code so that assignment to the output variable
occurs before the recursive call. In this example, assign a value to
out in the if block and perform the
recursive call in the else block.
function out = indirectRecurA_example1(x) if x<0 out = 0; else out = indirectRecurB(x-1)+1; end end function out = indirectRecurB(x) out = indirectRecurA_example1(x-1)+2; end
Alternatively, assign a dummy value to out before the
if block.
function out = indirectRecurA_error(x) if x>=0 out = indirectRecurB(x-1)+1; else out = 0; end end function out = indirectRecurB(x) out = indirectRecurA_error(x-1)+2; end