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.
Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates. When you use named and optional arguments, the arguments are evaluated in the order in which they appear in the argument list, not the parameter list.
You can assign an optional argument using the assignment operator in a function definition or using the Python **kwargs statement. There are two types of arguments a Python function can accept: positional and optional. Optional arguments are values that do not need to be specified for a function to be called.
Add a tilde to the input argument list so that the function ignores eventdata .
Define a function that accepts a variable number of input arguments using varargin . The varargin argument is a cell array that contains the function inputs, where each input is in its own cell.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With