Borrar filtros
Borrar filtros

How do I validate an input method input by a object property?

4 visualizaciones (últimos 30 días)
AAA
AAA el 1 de Sept. de 2023
Respondida: Matt J el 1 de Sept. de 2023
I am having a class "MY_CLASS" and want to write a method. In this method I first want to validate my inputs. The input is an array which should have the same size as given by one of my object properties. How can I implement this by using the arguments block?
classdef MY_CLASS
properties(Access=public)
Filenames cell {mustBeA(Filenames,"cell")} = {['Testrun_xxxx']}
Num_Files (1,1) uint32 {mustBeA(Num_Files,"uint32"), mustBePositive} = uint32(1)
end
methods
% Constructor
function obj = MY_CLASS( filenames, num_Files )
obj.Filenames = filenames;
obj.Num_Files = num_Files;
end
% function where I want to do my arguments validation
function obj = doSomething( obj, var1 )
arguments
obj
var1 (:,1) double {mustBeNumeric, mustBeSpecifiedSize( obj.Num_Files, var1 )}
end
.
.
.
end
end
end
% Validation Function
function mustBeSpecifiedSize( num_elements, array )
if not(num_elements == numel(array))
eidType = 'mustBeSpecifiedSize:invalidNumberOfElements';
msgType = 'Inconsistency issues at the number of elements.';
throwAsCaller(MException(eidType,msgType))
end
end
  2 comentarios
Matt J
Matt J el 1 de Sept. de 2023
Why not as you've written it now?
AAA
AAA el 1 de Sept. de 2023
Editada: AAA el 1 de Sept. de 2023
It gives me a syntax error for the obj.Num_Files function input: "Validators can only use previously declared positional arguments, the argument being validated, or literals."

Iniciar sesión para comentar.

Respuesta aceptada

Matt J
Matt J el 1 de Sept. de 2023
classdef myclass
properties(Access=public)
Filenames cell {mustBeA(Filenames,"cell")} = {['Testrun_xxxx']}
Num_Files (1,1) uint32 {mustBeA(Num_Files,"uint32"), mustBePositive} = uint32(1)
end
methods
% Constructor
function obj = MY_CLASS( filenames, num_Files )
obj.Filenames = filenames;
obj.Num_Files = num_Files;
end
% function where I want to do my arguments validation
function obj = doSomething( obj, var1 )
arguments
obj
var1 (:,1) double {mustBeNumeric, mustBeSpecifiedSize( obj, var1 )}
end
end
end
end
% Validation Function
function mustBeSpecifiedSize( obj, array )
num_elements=obj.Num_Files;
if not(num_elements == numel(array))
eidType = 'mustBeSpecifiedSize:invalidNumberOfElements';
msgType = 'Inconsistency issues at the number of elements.';
throwAsCaller(MException(eidType,msgType))
end
end

Más respuestas (0)

Categorías

Más información sobre Argument Definitions en Help Center y File Exchange.

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by