How to addParameter and validateattributes for several values at once (OOP)?
5 次查看(过去 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!