Selecting optional function parameters in MATLAB

Possible duplicate:
Matlab's default arguments

I have a function with about 7 parameters to pass. 3 of them are required, and the remaining 4 are optional. I want to pass only the first 3 and last parameter. How to do it?

Let's say that the function: the function [...] = fun (a, b, c, d, e, f, g)

a, b, c - necessary input data.

d, e, f, g - additional inputs.

I want to call fun and pass the values ​​for a, b, c and g.

In R, I can indicate this in a very neat way, for example: fun (a = 1, b = 4, c = 5, g = 0);

What is the equivalent syntax in matlab?

+3
source share
2 answers

Unfortunately, there is no way to do this. You must explicitly pass empty values ​​for parameters that you do not want to pass, and you need to check this condition in your function to see if the parameter passed or not, and if it is empty or not. Something like that:

function fun(a, b, c, d, e, f, g) if nargin<3 error('too few parameters'); end if nargin<4 || isempty(d) d = default_value; end % and so on... end % call fun(a, b, c, [], [], g); 

In the end, it may be easier to collect the optional parameters into one structure and check its fields:

 function fun(a, b, c, opt) if nargin<3 error('too few parameters'); end if nargin>3 if ~isfield(opt, 'd') opt.d = default_value; end end end % call opt.g = g; fun(a, b, c, opt); 

It is easier to call the function, and you do not need to specify empty parameters.

+5
source

The idiomatic way to do this in MATLAB is to use pairs of parameter pairs for optional arguments or a structure with additional fields specified. One way to do this is to use the helper class inputparser .

+2
source

All Articles