MATLAB: Two optional parameters mutually exclusive

optional parameter

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

Best Answer

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.