Two optional parameters mutually exclusive

조회 수: 21 (최근 30일)
Thales
Thales 2014년 9월 24일
댓글: Adam 2014년 9월 24일
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