Main Content

Output Variable Must Be Assigned Before Run-Time Recursive Call

Issue

You see one of these messages:

All outputs must be assigned before any run-time
recursive call. Output 'y' is not assigned here.

Simulink does not have enough information to determine output 
sizes for this block
.

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 call y = 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 the if block and the recursive call occurs in the else 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 z = callrec(n)
z = rec1(n);
end

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 z = callrec(n)
z = rec1(n);
end

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

Related Topics