Add function argument validation for optional parameters based on the values of required parameters

1 visualización (últimos 30 días)
I have a function signature like this:
function MyFunc(a, b, options)
%% Function argument validation
arguments
%% @Required parameters:
a (1,1) {mustBeInteger, mustBePositive}
b (1,1) {mustBeInteger, mustBePositive}
%% @Optional parameters:
options.n_bar (1,1) {mustBeInteger, mustBeLessThanOrEqual(options.n_bar, a*b*2)} % !!!Error!!!
end
% ... Function body of MyFunc goes here ...
I would like to add a constraint on options.n_bar based on the values of a and b, such that options.n_bar <= a*b*2. I tried to achieve that as shown in the above code snippet, but MATLAB didn't allow me to do that in this way. How can I make it work?

Respuesta aceptada

Steven Lord
Steven Lord el 23 de Feb. de 2022
Write your own local function that accepts n_bar, a, and b and performs the validation and use that local function as your validation function. This way your validation doesn't depend on the output of a function call (the * operator aka the mtimes function.)
MyFunc(1, 2) % Use the default of a*b*2
n_bar: 4
MyFunc(1, 2, 'n_bar', 5) % Error
Error using solution>MyFunc (line 10)
Invalid name-value argument 'n_bar'. Value must be less than or equal to 4.
function MyFunc(a, b, options)
%% Function argument validation
arguments
%% @Required parameters:
a (1,1) {mustBeInteger, mustBePositive}
b (1,1) {mustBeInteger, mustBePositive}
%% @Optional parameters:
options.n_bar (1,1) {mustBeInteger, validate_n_bar(options.n_bar, a, b)} = a*b*2;
end
% ... Function body of MyFunc goes here ...
disp(options)
end
function validate_n_bar(n_bar, a, b)
mustBeLessThanOrEqual(n_bar, a*b*2);
end

Más respuestas (0)

Categorías

Más información sobre Transaction Cost Analysis en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by