Two optional parameters mutually exclusive

21 次查看(过去 30 天)
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 个评论
Adam
Adam 2014-9-24
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!

请先登录,再进行评论。

采纳的回答

Geoff Hayes
Geoff Hayes 2014-9-24
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.

更多回答(2 个)

Guillaume
Guillaume 2014-9-24
编辑:Guillaume 2014-9-24
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 2014-9-24
编辑:Matt J 2014-9-24
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

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by