How to use property validation functions in class definitions for struct fields?

24 ビュー (過去 30 日間)
Davide
Davide 2024 年 4 月 12 日
コメント済み: Davide 2024 年 4 月 12 日
Hi,
I have a class in which I define a struct S. How can I validate that its fields (c1, c2, ...) are numeric? mustBeNumeric or mustBeUnderlyingType(S,"double") throw an error because they checks if S itself is numeric/double.
classdef myClass
properties
a {mustBeText} = ''
b {mustBeNumeric} = 0
S { ? } = struct('c1',0,'c2',0,'c3',0)
end
end
Thanks.

採用された回答

chicken vector
chicken vector 2024 年 4 月 12 日
編集済み: chicken vector 2024 年 4 月 12 日
If this is helpful, please remember to vote for best answer.
You can read this for more info.
classdef myClass
properties
a {mustBeText} = ''
b {mustBeNumeric} = 0
S {mustBeStructWith3NumericFields(S)} = struct('c1',0,'c2',0,'c3',0)
end
end
function mustBeStructWith3NumericFields(var)
if ~isstruct(var)
error("Input must be a struct.")
end
fn = fieldnames(var);
Nfn = length(fn);
if Nfn ~= 3
error("Input struct must have 3 fields.")
end
for j = 1 : Nfn
if ~isnumeric(var.(fn{j}))
error("Input struct fields must be numeric.")
end
end
end
You can run the following to test that your validator function performes its task correctly:
a = myClass;
S = struct('a',1,'b',2,'c',3);
a.S = S;
S = ["a" "b" "c"];
try
a.S = S;
catch ME
fprintf(ME.message + "\n");
end
S = struct('a',1,'b',2,'c',3,'d',4);
try
a.S = S;
catch ME
fprintf(ME.message + "\n");
end
S = struct('a',"1",'b',2,'c',3);
try
a.S = S;
catch ME
fprintf(ME.message + "\n");
end
  2 件のコメント
Stephen23
Stephen23 2024 年 4 月 12 日
編集済み: Stephen23 2024 年 4 月 12 日
Note that IF-ERROR can often be simplified using ASSERT, e.g.:
function mustBeStructWith3NumericFields(var)
assert(isstruct(var), "Input must be a struct.")
fn = fieldnames(var);
Nfn = length(fn);
assert(Nfn==3, "Input struct must have 3 fields.")
etc.
Davide
Davide 2024 年 4 月 12 日
Thanks! This is perfect

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

その他の回答 (0 件)

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by