jeff
jeff

Reputation: 13653

How to parse optional inputs in MATLAB?

I think inputparser is doing that, but I couldn't find an example that shows how.

In my function, I define a struct named opts which contain the parameters that control the function. Example :

function y = f(x, extraOpts)
  opts= struct( ...
   'N', 100, ...
   'visualize', 1, ... % etc
  ); 
  do_things(x, opts);
end

Fields of opts have default values, but I want to be able to change them selectively. So I want to call the function with something like this:

f(x, {'visualize', 0});

in which case .N remains 100 but .visualize becomes 0.

How can I achieve this with MATLAB? Also not sure if it will require the extraOpts parameter. I would of course prefer a way with function y = f(x) :)

Thanks for any help !

Upvotes: 3

Views: 342

Answers (2)

jeff
jeff

Reputation: 13653

I couldn't make the answer work, but I found another solution with inputParser, let me paste here for future reference :

function y = f2(extraOpts)
p = inputParser;
p.addParamValue('par1', 'defaultValue1');
p.addParamValue('par2', def2, @isnumeric);
p.addParamValue('par3', def3, @isnumeric);
p.parse(extraOpts{:});
extraOpts = p.Results;
end

the drawback is that I needed to separate the two inputs x and extraOpts and had to call f2 as a subroutine, defined in the same file as f. Maybe there is a more elegant way for this (i.e. one that does not require another function), but the example I have seen was also doing like that, and since it works, it's good for me :)

Upvotes: 0

Brock Hargreaves
Brock Hargreaves

Reputation: 872

You can use MATLAB's inputParser class:

http://www.mathworks.com/help/matlab/ref/inputparser-class.html http://blogs.mathworks.com/community/2012/02/13/parsing-inputs/

EDIT: I guess I'll just put the code in as well...

function y = f(x, extraOpts)
    p = inputParser;
    p.addRequired('x', @(x) length(x)>1);
    p.addOptional('visualize', 1, @isscalar);
    p.addOptional('N', 100, @isscalar);
    p.parse(x, extraOpts{:});
    do_things(x, extraOpts);
end

You might need to store the results of the parse, perhaps something along the lines of:

inputs = p.parse(x, extraOpts{:});
do_things(inputs)

END EDIT

Alternatively, you could do something like redefine your function to take the number of values in your struct though it's not as powerful as the input parser solution:

function y = f(N, visualize)
if nargin < 2
  visualize = 0
end
if nargin < 1
  visualize = 0
  N = 100
end

Upvotes: 5

Related Questions