How to input dependent parameters in matlab function?

조회 수: 8 (최근 30일)
cui,xingxing
cui,xingxing 2020년 11월 17일
댓글: cui,xingxing 2020년 11월 18일
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:

채택된 답변

Matt J
Matt J 2020년 11월 17일
편집: Matt J 2020년 11월 17일
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
cui,xingxing
cui,xingxing 2020년 11월 18일
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)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Downloads에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by