How to create an optional input parameter with special name?

303 Ansichten (letzte 30 Tage)
Mr M.
Mr M. am 27 Nov. 2014
Kommentiert: Aaron Mailhot am 3 Sep. 2020
I would like to use an optional input parameter. As far as I know, the standard solution is:
function myfunc(param1,param2,varargin)
however this is very ugly, because param1 and param2 can be named practically, but varargin is a system defined name. I understand, that in case of variable number of optional arguments this is not important, but for only one possible optional argument it would be practical to use a freely defined name. It is possible to solve this syntax problem somehow?

Antworten (2)

Geoff Hayes
Geoff Hayes am 27 Nov. 2014
Why not just call your optional third parameter as param3 and then check to see if it has been passed in or not? If the latter then you could initialize it to some default value. Something like
function myFunc(param1,param2,param3)
if ~exist('param3','var')
% third parameter does not exist, so default it to something
param3 = 42;
end
% remaining code
The above code checks to see if the third input exists or not. If not, then it is created and assigned a default value. The user can call your function as
myFunc(12, 23);
or as
myFunc(12,23,34);
  5 Kommentare
Aaron Mailhot
Aaron Mailhot am 3 Sep. 2020
@Richard: if you want to have 'arbitrary variance' in multiple optional parameters, I suggest arranging your function to utilize parameter-value pairs.
Its a little convoluted, and there are probably utilities to help with it, BUT it's not too bad to arrange it yourself directly at the end of the day. E.g. call it this way (where 10 and 30 are the e.g. specific values you want to use):
myFunc('-param1', 10, '-param3', 30)
And then the top of your function would go something like:
function test_params(varargin)
% Defaults
param1 = 1;
param2 = 2;
param3 = 3;
% Optionals
for ii = 1:2:nargin
if strcmp('-param1', varargin{ii})
param1 = varargin{ii+1};
elseif strcmp('-param2', varargin{ii})
param2 = varargin{ii+1};
elseif strcmp('-param3', varargin{ii})
param3 = varargin{ii+1};
end
end
% Test!
disp(param1)
disp(param2)
disp(param3)
% More stuff here
% ...
end
Aaron Mailhot
Aaron Mailhot am 3 Sep. 2020
For fun, you can even go nuts and call this with 'param3' first followed by 'param1'; it really is just 'users choice' now :).

Melden Sie sich an, um zu kommentieren.


Martin Krajda
Martin Krajda am 17 Okt. 2017
Bearbeitet: Martin Krajda am 17 Okt. 2017

Kategorien

Mehr zu Function Creation finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by