Add function argument validation for optional parameters based on the values of required parameters
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
hmhuang
le 23 Fév 2022
Réponse apportée : Steven Lord
le 23 Fév 2022
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?
Réponse acceptée
Steven Lord
le 23 Fév 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
MyFunc(1, 2, 'n_bar', 5) % Error
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
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Transaction Cost Analysis dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!