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.
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.