If you are writing a complex function that requires checking inputs, default argument values, key-value pairs, transfer options as structures, etc., you can use inputParser . This solution is probably too large for simple functions, but you can remember your monstrous function that solves equations, displays results, and brings you coffee. This is a bit like what you can do with python argparse .
You configure inputParser as follows:
>> p = inputParser(); >> p.addRequired('x', @isfinite) % validation function >> p.addOptional('y', 123) % default value >> p.addParamValue('label', 'default') % default value
Inside a function, you usually call it with p.parse(varargin{:}) and look for your parameters in p.Results . Some quick demo on the command line:
>> p.parse(44); disp(p.Results) label: 'default' x: 44 y: 123 >> p.parse() Not enough input arguments. >> p.parse(Inf) Argument 'x' failed validation isfinite. >> p.parse(44, 55); disp(p.Results) label: 'default' x: 44 y: 55 >> p.parse(13, 'label', 'hello'); disp(p.Results) label: 'hello' x: 13 y: 123 >> p.parse(88, 13, 'option', 12) Argument 'option' did not match any valid parameter of the parser.
Bas swinckels
source share