Documentation

Nonconstant Index intovararginorvarargoutin afor-Loop

Issue

Your MATLAB®code contains afor-loop that indexes intovararginorvarargout。当您生成代码时,您e this error message:

Non-constant expression or empty matrix. This expression must be constant because its value determines the size or class of some expression.

Cause

At code generation time, the code generator must be able to determine the value of an index intovararginorvaragout。Whenvararginorvaragoutare indexed in afor-loop, the code generator determines the index value for each loop iteration by unrolling the loop. Loop unrolling makes a copy of the loop body for each loop iteration. In each iteration, the code generator determines the value of the index from the loop counter.

The code generator is unable to determine the value of an index intovararginorvaragoutwhen:

  • The number of copies of the loop body exceeds the limit for loop unrolling.

  • Heuristics fail to identify that loop unrolling is warranted for a particularfor-loop. For example, consider the following function:

    function[x,y,z] = fcn(a,b,c)%#codegen[x,y,z] = subfcn(a,b,c);functionvarargout = subfcn(varargin) j = 0;fori = 1:nargin j = j+1; varargout{j} = varargin{j};end

    The heuristics do not detect the relationship between the indexjand the loop counteri。Therefore, the code generator does not unroll thefor-loop.

Solution

Use one of these solutions:

Force Loop Unrolling

Force loop unrolling by usingcoder.unroll。For example:

function[x,y,z] = fcn(a,b,c)%#codegen[x,y,z] = subfcn(a,b,c);functionvarargout = subfcn(varargin) j = 0; coder.unroll();fori = 1:nargin j = j + 1; varargout{j} = varargin{j};end

Rewrite the Code

Rewrite the code so that the code generator can detect the relationship between the index and the loop counter. For example:

function[x,y,z] = fcn(a,b,c)%#codegen[x,y,z] = subfcn(a,b,c);functionvarargout = subfcn(varargin)fori = 1:nargin varargout{i} = varargin{i};end

See Also

Related Topics