Home > Back-end >  Add function argument validation for optional parameters based on the values of required parameters
Add function argument validation for optional parameters based on the values of required parameters

Time:02-25

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?

CodePudding user response:

The only things allowed inside of validator function calls in arguments blocks are constant expressions like "string" or 123, or previously declared arguments.

This clarifies the dependencies between input arguments. This use case is a good candidate for a custom validator function.

function MyFunc(a, b, options)
    arguments
        a (1,1) {mustBeInteger, mustBePositive}
        b (1,1) {mustBeInteger, mustBePositive}
        options.n_bar (1,1) {myMustBeLessThanOrEqual(options.n_bar, a, b)}
    end
end
function myMustBeLessThanOrEqual(w, x, y)
    mustBeLessThanOrEqual(w, x*y*2);
end

The above custom validator myMustBeLessThanOrEqual contains supported expressions, and inside the custom validator any custom logic for validation can be used.

  • Related