Specific selection of methods depending on the class object size (scalar or array)

1 次查看(过去 30 天)
Hello community.
I am developping a class with quite a few methods. Some of these methods are useful when the class object is an array, for example to filter out individual objects that match certain conditions. Some of these methods only make sense when the object is a scalar.
I am trying to implement different behavior depending on the class object size.
I have tried a few things. First defining a parent class for array objects
classdef arrayclass < handle
properties
prop1
end
methods
% constructor
function obj = arrayclass(n)
obj.prop1 = 1; % scalar object
if n >1 % or array object
obj = [obj, obj];
end
if isscalar(obj) % if scalar object, try to build children class
obj = scalarclass(obj);
end
end
end
methods % shared methods between child and superclass
end
methods (Access = ?arrayClass) % methods exclusive to superclass
function arrayMethod(obj)
disp(obj.prop1 + 1)
end
end
end
and a child class for scalar objects
classdef scalarclass < arrayclass & matlab.mixin.Scalar
methods % methods exclusive to child
function obj = scalarclass(arrayObj) % constructor
obj.prop1 = arrayObj.prop1;
end
function scalarMethod(obj)
disp(obj.prop1)
end
end
end
I ran into some issues:
  • The scalar class calls the array class constructor and I run into issues. or infinite loop
  • Even if that would work, I don't know how to update the class type whenever the size changes:
a = arrayClass(2);
a(1).scalarMethod % wont be available since a is detected as arrayClass
Would you have any suggestion on how to proceed ?

回答(1 个)

Satwik
Satwik 2023-7-8
Hi Guillaume,
I understand that you want to create a class that has different behaviour based on whether the object is scalar or vector.
Your implementation of making a parent class for vector and then a child class for scalar methods can be reduced to just as single class by using function isscalar to check whether object is a scalar or vector.
For example if you call filter function and your object is a scalar then just just check with the isscalar function and return an error.
This single class implementation will be a lot easier to read and maintain.
Hope this helps!
isscalar documentaion for more details.

类别

Help CenterFile Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by