Clear Filters
Clear Filters

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

4 views (last 30 days)
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
AAA
AAA on 1 Sep 2023
Edited: AAA on 1 Sep 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."

Sign in to comment.

Accepted Answer

Matt J
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

More Answers (0)

Categories

Find more on Argument Definitions in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!