Optional args in MATLAB functions

FunctionMathMatlabParametersArguments

Function Problem Overview


How can I declare function in MATLAB with optional arguments?

For example: function [a] = train(x, y, opt), where opt must be an optional argument.

Function Solutions


Solution 1 - Function

There are a few different options on how to do this. The most basic is to use varargin, and then use nargin, size etc. to determine whether the optional arguments have been passed to the function.

% Function that takes two arguments, X & Y, followed by a variable 
% number of additional arguments
function varlist(X,Y,varargin)
   fprintf('Total number of inputs = %d\n',nargin);

   nVarargs = length(varargin);
   fprintf('Inputs in varargin(%d):\n',nVarargs)
   for k = 1:nVarargs
      fprintf('   %d\n', varargin{k})
   end

A little more elegant looking solution is to use the inputParser class to define all the arguments expected by your function, both required and optional. inputParser also lets you perform type checking on all arguments.

Solution 2 - Function

A simple way of doing this is via nargin (N arguments in). The downside is you have to make sure that your argument list and the nargin checks match.

It is worth remembering that all inputs are optional, but the functions will exit with an error if it calls a variable which is not set. The following example sets defaults for b and c. Will exit if a is not present.

function [ output_args ] = input_example( a, b, c )
if nargin < 1
  error('input_example :  a is a required input')
end

if nargin < 2
  b = 20
end

if nargin < 3
  c = 30
end
end

Solution 3 - Function

A good way of going about this is not to use nargin, but to check whether the variables have been set using exist('opt', 'var').

Example:

function [a] = train(x, y, opt)
    if (~exist('opt', 'var'))
        opt = true;
    end
end

See this answer for pros of doing it this way: https://stackoverflow.com/questions/8590478/how-to-check-whether-an-argument-is-supplied-in-function-call

Solution 4 - Function

Mathworks:Function Argument Validation

There is a detailed description about how to user optional parameters in function. Also, you can learn how to use function like build-in matlab fun like

> fun(arg1,'key1',value1)

There is some example using the trick from above:

function [a] = train(x,y,opt)
    arguments
        x double
        y double
        opt {mustBeNonempty} = true
        % this set the default value for opt is true
    end
    
    if opt
        a = 1;
    else
        a = x+y;
    end
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYekverView Question on Stackoverflow
Solution 1 - FunctionPraetorianView Answer on Stackoverflow
Solution 2 - FunctionMorganView Answer on Stackoverflow
Solution 3 - FunctionEvgeni SergeevView Answer on Stackoverflow
Solution 4 - Functionsid chenView Answer on Stackoverflow