Conditionals in argument blocks
24 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Is it possible to make the default value of one optional variable depend on the value of another optional variable?
In particular suppose I define a function with required argument shape and optional argument v1 so that when. The variable shape can take one of two names, and the variable v1 has different default values depending on the value of shape, or else can be specificed by a name value pair.
I should be able to make the calls
myFunction('rectangle')
and the arguments block should assign v1=[1 0].
If I make the call
myFunction('triangle')
and the arguments block should assign v1=[1 sqrt(3)]/2
But then I should be able to override the defaults with the calls
myfunction('rectangle',v1=[6 4])
or else
myfunction('rectangle',v1=[5 21])
and opts.v1 will take the value specified
0 Commenti
Risposta accettata
Lawrence
il 15 Mag 2022
Modificato: Lawrence
il 15 Mag 2022
This is possible because expressions are allowed as the default value, and you can use prior arguments in expressions for later arguments.
function v1 = myFunction(shape,v1)
arguments
shape {mustBeMember(shape,{'rectangle','triangle'})}
v1 (1,2) double = calculateDefaultV1(shape)
end
end
function v1 = calculateDefaultV1(shape)
switch shape
case 'rectangle'
v1 = [1 0];
case 'triangle'
v1 = [1 sqrt(3)]/2;
end
end
Note, however, that since Name/Value pairs can be supplied by the caller in any order or omitted entirely, you're not allowed to use the value of a name-value argument in an arguments block default value expression. So, this is illegal:
function v1 = bugged_myFunction(opts)
arguments
opts.shape {mustBeMember(opts.shape,{'rectangle','triangle'})}
opts.v1 (1,2) double = calculateDefaultV1(opts.shape) %% Cannot use opts.shape here
end
end
function v1 = calculateDefaultV1(shape)
switch shape
case 'rectangle'
v1 = [1 0];
case 'triangle'
v1 = [1 sqrt(3)]/2;
end
end
You'd need to either make shape a positional argument or hand-roll your default value like Chidvi Modala described in their answer, but using ~isfield(opts,'v1') instead of nargin or exist('v1','var').
0 Commenti
Più risposte (1)
Chidvi Modala
il 8 Giu 2021
You may refer to the following piece of code
function v1 = myfunction(shape, varargin)
if strcmp(shape,'rectangle')
if nargin >1
v1 = varargin{1};
else
v1=[1 0];
end
elseif strcmp(shape,'triangle')
if nargin >1
v1 = varargin{1};
else
v1=[1 sqrt(3)]/2;
end
end
end
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!