Documentation Center

  • Trial Software
  • Product Updates

Apply Operations to a Variable Number of Arguments

You can use varargin and varargout in for-loops to apply operations to a variable number of arguments. To index into varargin and varargout arrays in generated code, the value of the loop index variable must be known at compile time. Therefore, during code generation, the compiler attempts to automatically unroll these for-loops. Unrolling eliminates the loop logic by creating a separate copy of the loop body in the generated code for each iteration. Within each iteration, the loop index variable becomes a constant. For example, the following function automatically unrolls its for-loop in the generated code:

%#codegen
function [cmlen,cmwth,cmhgt] = conv_2_metric(inlen,inwth,inhgt)

[cmlen,cmwth,cmhgt] = inch_2_cm(inlen,inwth,inhgt);

function varargout = inch_2_cm(varargin)
for i = 1:length(varargin)
   varargout{i} = varargin{i} * 2.54;
end

When to Force Loop Unrolling

To automatically unroll for-loops containing varargin and varargout expressions, the relationship between the loop index expression and the index variable must be determined at compile time.

In the following example, the function fcn cannot detect a logical relationship between the index expression j and the index variable i:

%#codegen
function [x,y,z] = fcn(a,b,c)

[x,y,z] = subfcn(a,b,c);

function varargout = subfcn(varargin)
j = 0;
for i = 1:length(varargin)
    j = j+1;
    varargout{j} = varargin{j};
end

As a result, the function does not unroll the loop and generates a compilation error:

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

To fix the problem, you can force loop unrolling by wrapping the loop header in the function coder.unroll, as follows:

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

Using Variable Numbers of Arguments in a for-Loop

The following example multiplies a variable number of input dimensions in inches by 2.54 to convert them to centimeters:

%#codegen
function [cmlen,cmwth,cmhgt] = conv_2_metric(inlen,inwth,inhgt)

[cmlen,cmwth,cmhgt] = inch_2_cm(inlen,inwth,inhgt);

function varargout = inch_2_cm(varargin)
for i = 1:length(varargin)
   varargout{i} = varargin{i} * 2.54;
end

Key Points About the Example

  • varargin and varargout appear in the local function inch_2_cm, not in the top-level function conv_2_metric.

  • The index into varargin and varargout is a for-loop variable

For more information, see Variable Length Argument Lists for Code Generation.

Was this topic helpful?