3

Possible Duplicate:
Default Arguments in Matlab

I have a function with about 7 parameters to be passed. 3 of them are mandatory and the rest 4 are optional parameters. I want to pass only the first 3 and the last parameter. How do I do this?

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

a, b, c - required inputs.

d, e, f, g - optional inputs.

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

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

What is the equivalent syntax in matlab?

Community
  • 1
  • 1
Spectre
  • 682
  • 10
  • 26

2 Answers2

5

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

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 might 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 have to specify empty parameters.

angainor
  • 11,760
  • 2
  • 36
  • 56
3

The idiomatic way to do this in MATLAB is to use parameter-value pairs for optional arguments, or a struct with optional fields specified. One way to do this is to use the inputparser helper class.

Edric
  • 23,676
  • 2
  • 38
  • 40