MATLAB Answers


How to support default parameter in MATLAB FUNCTION ?

Asked by M.K.H. CHANDAN on 18 May 2015
Latest activity Edited by M.K.H. CHANDAN on 19 Nov 2015
1 . As I know , there is no default parameter support on MATLAB FUNCTION like other high level programming language c,c++, Is there any other methodology through which it can be done like other compiler C,C++? or programmer has to do using his own logic through varargin.


Sign in to comment.

2 Answers

Answer by Stephen Cobeldick on 18 May 2015
Edited by Stephen Cobeldick on 18 May 2015
 Accepted Answer

MATLAB is an interpreted language, not a compiled language, so there is no compiler as such.
In any case there is no inbuilt syntax to allow such things as:
function out = fun(val_1=def_val, val_2=def_val2, ...)
But you could use the input parser class, or use one of the methods listed here:
The most common ways of dealing with this are:
  • Use nargin and some switch or if statements to detemrine the default parameters.
  • Use varargin and logical indexing to detect non-specified arguments (e.g. empty).
  • Use key-value pairs (usually with varargin) and strcmpi to detect the keys.
  • Use a scalar structure to hold all options.
Using varargin with nargin or logical indexing is very easy:
function foobar(varargin)
Defaults = {A,B,C...};
Defaults(1:nargin) = varargin;
function foobar(varargin)
Defaults = {A,B,C...};
idx = ~cellfun('isempty',varargin);
Defaults(idx) = varargin(idx);
MATLAB themselves use different methods in different functions. Have a look at the ODE functions to see the structure syntax, many plotting functions use the key-value syntax.
You can easily combine key-value and scalar-structure in one function, see my FEX submission here to see how:

  1 Comment

Yes, It is a nice idea, on programer way Defaults(1:nargin) = varargin; we can solve it , also we can store it on an cell array and can be used for further use.

Sign in to comment.

Answer by Ingrid
on 18 May 2015

in your function you need to check how many parameters have been passed
function myFunction(variable1,variable2, optionalVarChangeDefaultParam)
if nargin > 2
defaultParam = optionalVarChangeDefaultParam;
defaultParam = 2;

  1 Comment

Yes , It is programmer way , but MATLAB does not support like function myFunction(variable1,variable2,... optionalVarChangeDefaultParam1 =3, ... optionalVarChangeDefaultParam2 =4 , ... optionalVarChangeDefaultParam4 =5)

Sign in to comment.