Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional args in MATLAB functions

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.

like image 370
Yekver Avatar asked Jul 20 '11 15:07

Yekver


People also ask

What is an optional argument in functions?

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.

How do you make an argument in a function optional?

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.

How do you skip input arguments in MATLAB?

Add a tilde to the input argument list so that the function ignores eventdata .

What is args in MATLAB?

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.


1 Answers

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.

like image 68
Praetorian Avatar answered Sep 19 '22 15:09

Praetorian