How to input dependent parameters in matlab function?
13 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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:
0 Kommentare
Akzeptierte Antwort
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
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Downloads finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!