필터 지우기
필터 지우기

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

조회 수: 4 (최근 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에서 Assembly에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by