0

I have two subclasses:

  • Line
  • Arc

Their objects will be creating a path by appending them on their end. These have their own "plotCurve" methods. I want to store these objects in an array in order such as:

path = [line1,line2,arc1,line3,arc2,arc3,line4,arc4,arc5...];

(I think "path" should be the object of superclass "Path") when I code something like;

for i=1:size(path)
    path(i).plotCurve;
    hold on
end

the result should be shown. I should be able to see the whole path. (So, when the object of "Line" comes "plotCurve" method should be run and same for Arc objects).

  • What data type/variable type are we expecting line and arc to be? – MichaelTr7 Jul 30 '20 at 05:49
  • those are classes, there are 10-15 float properties for each. – controlsHeaven Jul 30 '20 at 05:54
  • No need for inheritance in this case. Make `path` a cell array, you can populate that with objects of the two classes (or anything else). Then you can call the `plotCurve` method of each object, as long as the object defines such a method, it will work. – Cris Luengo Jul 30 '20 at 07:03
  • @CrisLuengo yes you are right. Thats actually how I already did. However, I would like to know how to do it without using cell arrays using oop. – controlsHeaven Jul 30 '20 at 07:13

2 Answers2

2

It looks like subclassing from matlab.mixin.Heterogeneous allows this behaviour:

classdef Path < matlab.mixin.Heterogeneous
%...
end

classdef Line < Path
%...
end

classdef Arc < Path
%...
end

path = [Line,Line,Arc,Line,Arc,Arc];

figure, hold on
for i=1:numel(path)
    path(i).plotCurve;
end

I found this here: https://www.mathworks.com/matlabcentral/answers/4354-matlab-handle-class-violates-polymorphism-on-handle-equivalence

Though I think it's easier to make path a cell array, there is no difference in behavior in the code above, except using different indexing: path{i}.plotCurve.

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
2

Further to @Cris's suggestion, I would suggest a refinement a bit like this (untested)

classdef Path < matlab.mixin.Heterogeneous
    methods (Abstract, Access = protected)
        plotOne(obj)
    end
    methods (Sealed)
        function plotAll(objs)
            figure; hold on;
            for obj = objs(:).' % loop over all elements
                plotOne(obj);
            end
        end
    end 
end

This lets you call the plotAll method on an array of Path - that method must be Sealed. It unwraps the array to call the indivual plotOne methods on each element.

Edric
  • 23,676
  • 2
  • 38
  • 40
  • Hi, sorry for digging out an old post. Does this work for you? I'm getting the error message `Cannot call method 'plotOne' because 'obj' is heterogeneous and 'plotOne' is not sealed.` So it seems that also plotOne must be sealed. – mincos Jun 09 '23 at 13:07
  • You must ensure you call `plotOne` with a scalar instance... – Edric Jun 11 '23 at 15:21