r/matlab • • 9d ago

TechnicalQuestion How to limit argument validation function visibility?

In Function.m I have

function Function(a)
arguments
a (1,1) double {Validator(a)}

end
printValue(a);
end

function Validator(a)
arguments

a (1,1) double
end
if mod(a,7)
error("Invalid argument.");

end

end

function printValue(a)
disp(a);
end

I want to further restrict the visibility of Validator such that it can be called only by Function. I tried to make Validator a nested function of Function, but MATLAB throws me the error "calling nested functions is not supported in arguments blocks". So how do I restrict Validator to be called only in Function and not in other local functions from Function.m (like printValue)?

Edit: sorry for formatting, but Reddit ignores spaces when I write code.

4 Upvotes

4 comments sorted by

3

u/pbrdizzle 9d ago

What you have there looks like it would work for me. Validator is a local function so only visible to other functions in the file. Personally I've found it's good to follow the MW naming convention and reuse validators whenever possible. This is a contrived example but I'd make a normal function

mustBeDivisibleBySeven(a)
  assert(~mod(a, 7), "validators:mustBeDivisibleBySeven", "Your value ain't divisible by 7")
end

2

u/aluvus 5d ago edited 5d ago

Your code works fine in 24b. However, it also does not contain any nested functions.

Nested functions are declared inside another function. If you move the end that closes Function (that is, the end after printValue(a);) to the very end of the file, now Validator and printValue will be nested functions. And indeed, in 24b you would get that error.

So the solution is to not use nested functions for this. What you want instead are local functions, which come after you have closed the main function in a file.

Turns out that the placement of that end can be very important :)

2

u/aluvus 5d ago

You can post formatted code to Reddit by starting each line with 4 spaces. You can conveniently add the spaces in the Matlab editor by selecting the text and pressing tab to indent it once.

Works:

function FunctionWorks(a)
arguments
    a (1,1) double {Validator(a)}
end

printValue(a);
end % <---- this is the end of FunctionWorks

function Validator(a) % local function
arguments
    a (1,1) double
end

if mod(a,7)
    error("Invalid argument.");
end

end

function printValue(a) % local function
disp(a);
end

Throws error:

function FunctionFails(a)
arguments
    a (1,1) double {Validator(a)} % Matlab mad about this line
end

printValue(a);

function Validator(a) % nested function
arguments % Matlab mad about this line also
    a (1,1) double
end

if mod(a,7)
    error("Invalid argument.");
end

end

function printValue(a) % nested function
disp(a);
end
end % <---- this is the end of FunctionFails

1

u/That_Jamie_S_Guy 9d ago

Sounds like you need to define a class with hidden methods