MATLAB: Using one variable containing all name-value pairs for built-in Matlab functions

argumentsinputparsername-value pairs;structexpandvarargin

I want to give users of my code the option to specify name-value pairs when/if they care about them, but if they don't specify them, let Matlab use default values.
For example, a user might enter an options structure for an SVM classifier such as:
Options.kernel = 'rbf';
Options.kernelScale = 0.15;
Then my program would train an SVM classifier using these parameters:
svmModel = fitcsvm(observations, labels, 'KernelFunction', Options.kernel, 'KernelScale', Options.kernelScale)
But if the user only enters the options structure with the 'kernel' field, then my program would call
svmModel = fitcsvm(observations, labels, 'KernelFunction', Options.kernel)
leaving the kernel scale as the default. The issue comes down to how to do this elegantly. I can check all the field names of the Options structure, looking for name value pairs to assign, e.g.
if any(strcmp('kernel', fieldnames(Options)))
if strcmp('rbf', Options.kernel) && any(strcmp('kernelScale', fieldnames(Options)))
svmModel = fitcsvm(observations, labels, 'KernelFunction', Options.kernel, 'KernelScale', Options.kernelScale);
else
svmModel = fitcsvm(observations. labels, 'KernelFunction', Options.kernel);
end
end
But this can quickly get unwieldy for built-in functions with lots of options. Is there a better way? What I'd like to do is send in a single variable with all the name-value pairs, but when I do this, Matlab interprets varargin as being one value not a set of name-value pairs, e.g.
% Set up parameters for model
nameValuePairs = {'KernelFunction', Options.kernel};
switch Options.kernel
case {'rbf', 'gaussian'}
if any(strcmp('kernelScale', fieldnames(Options)))
nameValuePairs = cat(2, nameValuePairs, ...
{'KernelScale', Options.kernelScale});
end
case {'polynomial'}
if any(strcmp('polynomialOrder', fieldnames(Options)))
nameValuePairs = cat(2, nameValuePairs, ...
{'PolynomialOrder', Options.polynomialOrder});
end
end
% Train
svmModel = fitcsvm(observations, labels, nameValuePairs);
Is there a way to make Matlab interpret a single variable as a set of name-value pairs? Many thanks for any thoughts on this!

Best Answer

See inputParser
which by default will expand structures into Name-Value pairs for you automatically. Note, however, that you have the option of turning this behavior off,