matlabfunctionvariadic-functionsoptional-parametersname-value

Variable argument pairs in MATLAB functions


I'm trying to develop a function that contains multiple arguments. To be as robust as possible, I want to be able to call my function as follows:

foo( x, y, z, 'OptionalArg1', bar, 'OptionalArg2', blah, 'OptionalArg3', val )

I want my function to be robust enough to contain any combination of these arguments in any order. I also need to be able to set defaults if the argument is not provided. Is there a standard way to do this in MATLAB?


Solution

  • The best way would be to use the inputParser class, with the addParameters function.

    In short, your code would look like:

    function foo(x,y,z,varargin)
    
    p=inputParser;
    
    validationFcn=@(x)isa(x,'double')&&(x<5); % just a random example, add anything
    addParameter(p,'OptionalArg1',defaultvalue, validationFcn);
    % same for the other 2, with your conditions
    
    %execute
    parse(p,varargin{:});
    
    % get the variables
    bar=p.Results.OptionalArg1;
    % same for the other 2
    
    
    % foo
    

    Alternatively, you could write your own as I did (example here). The code there is easily modifiable to have your own input parser (you just need to change the opts, and add a switch for each new opt.

    But the inputParser is easier, and clearer to use.