Function Argument Validation, Compare to Irrational Number or Expression

Is there a way to use MATLAB's built-in validation functions to compare an argument to an expression or funciton output?
I want to do the following:
function out = myfun(x)
arguments
x (1,1) double {mustBeGreaterThan(x,pi)}
end
out = foo;
end
Since pi is a function, which is not allowed in the native validation functions, the above code throws an error. Instead I have to define a custom validation function to compare the argument to pi.
function out = myfun(x)
arguments
x (1,1) double {mustBeGreaterThanPi(x)}
end
out = foo;
end
function mustBeGreaterThanPi(x)
if x <= pi
error('Value must be greater than pi.')
end
end
The validation block cannot pass pi to the custom validation function, so pi must be built into the function. This is a complete pain in the neck if we want to compare, say, ten arguments to ten different irrationals, repeating decimals, or simple expressions; we must define ten custom validation functions, unless we get creative with passing scalars or strings (we could pass c to the validation function where an error is thrown if value <= c*pi, for example).

 Respuesta aceptada

Adam Danz
Adam Danz el 28 de Abr. de 2020
Editada: Adam Danz el 29 de Abr. de 2020
One solution would be to replace the pi function with a literal;
arguments
x (1,1) double {mustBeGreaterThan(x,3.1415926535897932384626)}
end
or you could use a different form of validation,
function out = jff(x)
assert(x>pi, 'x must be greater than pi')
out = x*2;
end
function out = jff(x)
validateattributes(x,{'double'},{'scalar','>',pi})
out = x*2;
end

4 comentarios

Accepted because these are all decent work arounds, and I'm pretty sure the answer to my original question is "no." It seems like allowing functions (or at least basic arithmetic) in argument validation would be a sensible feature to include in a future release.
Agreed. The arguments method of input validation is still new (released in r2019b) so perhaps it will be expanded upon in future releases. Most of my functions are designed to run in as many releases of Matlab as possible so I haven't used the arguments method of validation. I suggest you make a service request for this feature.
I didn't realize it was that recent. I'll submit a request.
Just an FYI, you can see when a function was first released at the bottom of the documentation page.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Argument Definitions en Centro de ayuda y File Exchange.

Productos

Versión

R2019b

Preguntada:

el 28 de Abr. de 2020

Comentada:

el 29 de Abr. de 2020

Community Treasure Hunt

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

Start Hunting!

Translated by