How to input dependent parameters in matlab function?

6 vues (au cours des 30 derniers jours)
cui,xingxing
cui,xingxing le 17 Nov 2020
Commenté : cui,xingxing le 18 Nov 2020
I encountered such an input parameter dependency problem in my project. How can I solve it in an elegant way through "arguments"?
function out = myfun(A,B,optionC,dependent_C1,dependent_C2,...)
arguments
% If I enter optionC, one of dependent_C1 and dependent_C2 must be entered; otherwise, if optionC is not entered, neither dependent_C1, dependent_C2 can be entered
end
end
The syntax format is:
out = myfun(A,B)
out = myfun(A,B,optionC,dependent_C1)
out = myfun(A,B,optionC,dependent_C2)
The impossible formats are:
out = myfun(A,B,optionC)
out = myfun(A,B,optionC,dependent_C1,dependent_C2)
--------------------
similar question:

Réponse acceptée

Matt J
Matt J le 17 Nov 2020
Modifié(e) : Matt J le 17 Nov 2020
These two,
out = myfun(A,B,optionC,dependent_C1)
out = myfun(A,B,optionC,dependent_C2)
are not possible simultaneously. If you want an argument to be non-positional, it must be entered as a Name-Value pair. The way to do approximately what you want is to support the following syntaxes, with the rule that dependent_C1 and dependent_C2 cannot both be empty,
out = myfun(A,B,optionC,dependent_C1)
out = myfun(A,B,optionC,dependent_C1,[])
out = myfun(A,B,optionC,[],dependent_C2)
out = myfun(A,B,optionC,dependent_C1,dependent_C2)
To handle the above, my approach would be as below. I don't think the arguments block can achieve something simpler.
function out = myfun(A,B,varargin)
arguments
A ...
B ...
end
if nargin>=3
varargin(end+1:5)={[]};
[optionC,dependent_C1,dependent_C2]=deal(varargin{3:5});
assert( ~isempty(dependent_C1) || ~isempty(dependent_C2), 'Bad argument combination')
end
end
  1 commentaire
cui,xingxing
cui,xingxing le 18 Nov 2020
thanks,I think the best design method(Name-Value pair) should be:
function out = myfun(A,B,options)
arguments
A ...
B ...
options.name (1,1) string {mustBeMember(options.name,["dependent_C1","dependent_C2"])} = "dependent_C1"
end
end
The syntax format is:
out = myfun(A,B)
out = myfun(A,B,'name',dependent_C1)
out = myfun(A,B,'name',dependent_C2)

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Downloads dans Help Center et File Exchange

Produits


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by