Main Content

Specify Number of Entry-Point Function Input or Output Arguments to Generate

You can control the number of input or output arguments in a generated entry-point function. From one MATLAB® function, you can generate entry-point functions that have different signatures.

Control Number of Input Arguments

If your entry-point function uses varargin, specify the properties for the arguments that you want in the generated function.

Consider this function:

function [x, y] = myops(varargin)
%#codegen
if (nargin > 1)
    x = varargin{1} + varargin{2};
    y = varargin{1} * varargin{2};
else
    x = varargin{1};
    y = -varargin{1};
end

To generate a function that takes only one argument, provide one argument with -args.

codegen myops -args {3} -report

If you use the MATLAB Coder™ app:

  1. On the Define Input Types page, click Let me enter input or global types directly.

  2. To add an argument, in the variables table, to the right of varargin, click Plus button.

    App window, showing definition of varargin

  3. Specify the properties for each argument.

    App window, showing properties of varargin

If you generate code by using codegen, you can also control the number of input arguments when the MATLAB function does not use varargin.

Consider this function:

function [x, y] = myops(a,b)
%#codegen
if (nargin > 1)
    x = a + b;
    y = a * b;
else
    x = a;
    y = -a;
end

To generate a function that takes only one argument, provide one argument with -args.

codegen myops -args {3} -report

Control the Number of Output Arguments

If you generate code by using codegen, you can specify the number of output arguments by using the -nargout option.

Consider this function:

function [x, y] = myops(a,b)
%#codegen
x = a + b;
y = a * b;
end

Generate a function that has one output argument.

codegen myops -args {2 3} -nargout 1 -report

You can also use -nargout to specify the number of output arguments for an entry-point function that uses varargout.

Rewrite myops to use varargout.

function varargout = myops(a,b)
%#codegen
varargout{1} = a + b;
varargout{2} = a * b;
end

Generate code for one output argument.

codegen myops -args {2 3} -nargout 1 -report

If you use the MATLAB Coder app, to specify the number of outputs when a function returns varargout or to generate fewer outputs than the function defines:

  1. On the Define Input Types page, define the input types manually or by using Autodefine Input Types.

  2. In Number of outputs, select the number.

App window, showing definitions of variables a and b

Related Topics