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

1 view (last 30 days)
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 ?

Answers (1)

Satwik
Satwik on 8 Jul 2023
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.

Categories

Find more on Construct and Work with Object Arrays in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!