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

6 ビュー (過去 30 日間)
AAA
AAA 2023 年 9 月 1 日
回答済み: Matt J 2023 年 9 月 1 日
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 件のコメント
Matt J
Matt J 2023 年 9 月 1 日
Why not as you've written it now?
AAA
AAA 2023 年 9 月 1 日
編集済み: AAA 2023 年 9 月 1 日
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."

サインインしてコメントする。

採用された回答

Matt J
Matt J 2023 年 9 月 1 日
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 件)

カテゴリ

Help Center および File ExchangeProperties についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by