How to input dependent parameters in matlab function?

13 Ansichten (letzte 30 Tage)
cui,xingxing
cui,xingxing am 17 Nov. 2020
Kommentiert: cui,xingxing am 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:

Akzeptierte Antwort

Matt J
Matt J am 17 Nov. 2020
Bearbeitet: Matt J am 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 Kommentar
cui,xingxing
cui,xingxing am 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)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Downloads finden Sie in Help Center und File Exchange

Produkte


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by