3

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. E.g., 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

3 Answers 3

5

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 forloop.

(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{:})
Sign up to request clarification or add additional context in comments.

Comments

2

You can do it in following way:

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

Comments

1

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.

2 Comments

This answer does not answer the question.
Yeah, I misunderstood the question, I assumed the person asking the question would know about {:}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.