Two optional parameters mutually exclusive

13 views (last 30 days)
Hello,
the question is pretty simple. I have a function with two optional parameters:
y = f(x,opt1,opt2)
The user may provide either opt1 or opt2, but not both. In the function, I want to create an array with either lenght opt1 or step size opt2, so the user can only provide one of the optional parameters:
if opt1
v = linspace(a,b,opt1)
end
if opt2
v = a:opt2:b
end
How to proceed?
Thank you, Thales
  1 Comment
Adam
Adam on 24 Sep 2014
Plenty of acceptable options below. I would hesitate to suggest anything without knowing the usage of the function better. I like Guillaume's answer, but I tend to be fussy about function signatures and like parameters and arguments to be intuitively named so would probably ask the calling function to pass in either 'length' or 'step' rather than 'opt1' or 'opt2'.
But then again that depends on what the calling function 'knows'. It may be that the best solution is for the calling function itself to create the vector v by its chosen method and just pass it in as one single unequivocal argument.
The problem of defining a regular grid, which looks similar to what you are doing, always causes me problems though when I want to define a start and then either a size and an end, a step and an end or a step and a size to parameterise the grid!

Sign in to comment.

Accepted Answer

Geoff Hayes
Geoff Hayes on 24 Sep 2014
Thales - you could just pass a structure as the second input to your function, and depending upon which field has been defined, use that to determine what code gets executed (length vs step)
function y = f(x,params)
if isfield(params,'opt1')
v = linspace(a,b,params.opt1);
elseif isfield(params,'opt2')
v = a:params.opt2:b;
end
% etc.
The function could be called then as
y=f(42, struct('opt1',102));
y=f(42, struct('opt2',102));
The structure could be defined before you call the function, or as above.

More Answers (2)

Guillaume
Guillaume on 24 Sep 2014
Edited: Guillaume on 24 Sep 2014
The 'standard' way of doing this in matlab is:
function y = f(x, option, value)
switch option
case 'opt1' %'length' would be a better name
v = linspace(a,b,value);
case 'opt2' %'step' would be a better name
v = a:value:b;
otherwise
error('invalid option name: %s', option);
end
%...
end

Matt J
Matt J on 24 Sep 2014
Edited: Matt J on 24 Sep 2014
How about something like this
function y = f(x,opt1,opt2)
if nargin<3,
opt2=[];
end
if nargin<2
opt1=[];
end
if xor(isempty(opt1), isempty(opt2))
error 'One and only one argument must be empty'
elseif ~isempty(opt1)
v = linspace(a,b,opt1)
elseif ~isempty(opt2)
v = a:opt2:b
end

Community Treasure Hunt

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

Start Hunting!