How to input dependent parameters in matlab function?

6 visualizaciones (últimos 30 días)
cui,xingxing
cui,xingxing el 17 de Nov. de 2020
Comentada: cui,xingxing el 18 de Nov. de 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:

Respuesta aceptada

Matt J
Matt J el 17 de Nov. de 2020
Editada: Matt J el 17 de Nov. de 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 comentario
cui,xingxing
cui,xingxing el 18 de Nov. de 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)

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Downloads en Help Center y File Exchange.

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by