Add function argument validation for optional parameters based on the values of required parameters
1 view (last 30 days)
Show older comments
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?
Accepted Answer
Steven Lord
on 23 Feb 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 Comments
More Answers (0)
See Also
Categories
Find more on Transaction Cost Analysis in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!