Search code examples
matlabsyntaxargument-validation

Import a custom validation function for use in the arguments block


I have a function file my_function.m that uses function argument validation:

function b = my_function(a)
    arguments
        a (1, 1) double {mustBeReal}
    end
    b = a + 1;
end

I have written a custom validation function (as an example), in a namespaced package, so its fully qualified name is something like mypackage.foo.mustBeSomething.

I want to be able to import the name mustBeSomething immediately for use in the arguments block.

import mypackage.foo.mustBeSomething;

But MATLAB doesn't let me place it anywhere sane:

  • Placing it in the first line before the function keyword causes MATLAB to interpret my_function as a local function
  • Placing it in the line after function but before arguments causes MATLAB to complain that the arguments block must come first
  • Placing it in after the arguments keyword but before the a line causes MATLAB to interpret import as an argument name

Is there really no way I can use just mustBeSomething, instead of the fully qualified name through an import?

function b = my_function(a)
    arguments
        a (1, 1) double {mustBeReal, mypackage.foo.mustBeSomething}
    end
    b = a + 1;
end

Solution

  • From the Function Argument Validation documentation:

    Restrictions on Variable and Function Access

    arguments blocks exist in the function's workspace. Any packages, classes, or functions added to the scope of the function using the import command are added to the scope of the arguments block.

    So you can just import in the function code block to use with the arguments block.

    function b = my_function(a)
        arguments
            a (1, 1) double {mustBeReal, mustBeSomething}
        end
        import mypackage.foo.mustBeSomething
        b = a + 1;
    end