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

1 次查看(过去 30 天)
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?

采纳的回答

Steven Lord
Steven Lord 2022-2-23
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Transaction Cost Analysis 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by