How to addParameter and validateattributes for several values at once (OOP)?
6 ビュー (過去 30 日間)
古いコメントを表示
Basically I have the MainObject and I want to add to this object the Obj1 (FilterObj) e Obj2 (RotObj). When I just need to add one object I do something like:
function set.PipeBolt(obj,val)
if ~isempty(val)
validateattributes(val, {'FilterObj'},{'size',[NaN,1]});
else
val = FilterObj.empty;
end
obj.PipeBolt = val;
end
and in constructer something like
addParameter(parser,'PipeBolt',FilterObj.empty,@(x)validateattributes(x,'{FilterObj'},'PipeLineBolt','PipeBolt'))
let say that FilterObj is Obj1 but for Obj1 (RotObj) how can I adjust the code to pass and validate atributes both types of objects?
0 件のコメント
回答 (1 件)
Sameer
2025 年 5 月 30 日
Hi @Armindo
To accept and validate multiple object types in an "addParameter" call and using "validateattributes", the input validation function can be adjusted to accept either of the desired classes.
Since "validateattributes" does not directly support checking for multiple classes at once, a custom anonymous function can be used instead. For example, to accept both "FilterObj" and "RotObj", the input can be validated using "isa" within the validation function.
In the constructor, this can be done as follows:
addParameter(parser, 'PipeBolt', [], ...
@(x) isa(x, 'FilterObj') || isa(x, 'RotObj'));
If the input can also be an array of objects, "arrayfun" can be used to check each element:
addParameter(parser, 'PipeBolt', [], ...
@(x) all(arrayfun(@(obj) isa(obj, 'FilterObj') || isa(obj, 'RotObj'), x)));
In the setter method, similar logic can be used:
function set.PipeBolt(obj, val)
if ~isempty(val)
if ~all(arrayfun(@(obj) isa(obj, 'FilterObj') || isa(obj, 'RotObj'), val))
error('Each element must be a FilterObj or RotObj');
end
else
val = FilterObj.empty;
end
obj.PipeBolt = val;
end
This approach allows the property to accept an array of either "FilterObj", "RotObj", or both, while validating the input properly.
Hope this helps!
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Specify Design Requirements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!