简体   繁体   中英

Pass several 'Name, Value' parameters to a MATLAB function

I am trying to figure out how I can pass several optional 'Name','Value' pair parameters to a MATLAB function like this: https://es.mathworks.com/help/stats/fitcknn.html

I mean, my parameters are stored in a struct, but this struct does not always contain the same number of parameters pair. Eg, I can have the following struct:

options.NumNeighbors = 3
options.Standardize = 1;

So, the function calling would be:

output = fitcknn(X,Y,'NumNeighbors',options.NumNeighbors,'Standardize',options.Standardize);

But, another time I could have:

options.NumNeighbors = 3
options.Standardize = 1;
options.ScoreTransform = 'logit';

And thus, the function calling will have another parameter pair:

output = fitcknn(X,Y,'NumNeighbors',options.NumNeighbors,'Standardize',...
options.Standardize,'ScoreTransform',options.ScoreTransform);

What I want is to dynamically call the function without worrying about the final number of pair 'Name'-'Value' parameters. I have tested something like this, but it does not work:

options = {'NumNeighbors',3,'Standardize',1};
output = fitcknn(X,Y,options);

Any ideas?

Thanks in advance

You could use a comma-separated list as input. So just add a {:} to your option input.

options = {'NumNeighbors',3,'Standardize',1};
output = fitcknn(X, Y, options{:});

The options input could be generated from the struct by a simple for loop.

(In the example below I'm using listdlg instead of fitcknn as I currently could not obtain the toolbox)

options.ListString = {'a','b'};
options.Name = 'Test';
options.ListSize = [200 300];

optInput = {};
for optField = fieldnames(options)'
    optInput{end+1} = char(optField);
    optInput{end+1} = options.(char(optField));
end
listdlg(optInput{:})

Use the varargin function in your function declaration. It collects all extra inputs into a cell array that you can parse inside your function.

Your function declaration will look like this:

function [out]=myfunc(in1,in2,varargin)
% in1 and in2 are mandatory inputs

and you would call your function like this:

[out]=myfunc(in1,in2,optionalIn1,optionalIn2,...,optionalInN)

You would then get a cell array varargin in your function's workspace where:

varargin{1}=optionalIn1;
varargin{2}=optionalIn2;
...
varargin{N}=optionalInN;

You can then parse this to suit your needs.

You can do it in following way:

options = {'NumNeighbors',3,'Standardize',1};
output = fitcknn(X,Y,options{:});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM