How do I validate an input method input by a object property?
6 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Matt J
on 1 Sep 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
0 Comments
More Answers (0)
See Also
Categories
Find more on Properties in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!