How to deal with name/value pairs of function arguments in MATLAB

Posted by Richie Cotton on Stack Overflow See other posts from Stack Overflow or by Richie Cotton
Published on 2010-05-05T17:03:07Z Indexed on 2010/05/05 21:48 UTC
Read the original article Hit count: 205

Filed under:

I have a function that takes optional arguments as name/value pairs.

function example(varargin)
% Lots of set up stuff
vargs = varargin;
nargs = length(vargs);
names = vargs(1:2:nargs);
values = vargs(2:2:nargs);

validnames = {'foo', 'bar', 'baz'};    
for name = names
   validatestring(name{:}, validnames);
end

% Do something ...
foo = strmatch('foo', names);
disp(values(foo))
end

example('foo', 1:10, 'bar', 'qwerty')

It seems that there is a lot of effort involved in extracting the appropriate values (and it still isn't particularly robust again badly specified inputs). Is there a better way of handling these name/value pairs? Are there any helper functions that come with MATLAB to assist?

© Stack Overflow or respective owner

Related posts about matlab