1

this page Designing Heterogeneous Class Hierarchies tells us that we can put two obects belonging to different subclass but same super class into an array.

But in my program, it doesn't work. In my program, I create a super class 'Agent' and two subclass 'Agent_XY' and 'Agent_XZ' inheriting 'Agent'. I let A to be an Agent_XY object and B to be an Agent_XZ object. And I try to put this two objects into an array.

classdef Agent < handle

    properties
        inventory_X
        inventory_Y
        inventory_Z
    end
    methods
        function obj = Agent(inventory_x,inventory_y,inventory_z)
            obj.inventory_X = inventory_x;
            obj.inventory_Y = inventory_y;
            obj.inventory_Z = inventory_z;
        end
    end
end
classdef Agent_XY < Agent
    properties

    end

    methods
        function obj = Agent_XY(inventory_x,inventory_y,inventory_z)
           obj = obj@Agent(inventory_x,inventory_y,inventory_z)
        end
    end
end
classdef Agent_XZ < Agent
    properties

    end

    methods
        function obj = Agent_XZ(inventory_x,inventory_y,inventory_z)
           obj = obj@Agent(inventory_x,inventory_y,inventory_z)
        end
    end
end
A=Agent_XY(1,2,3)

A = 

  Agent_XY with properties:

    inventory_X: 1
    inventory_Y: 2
    inventory_Z: 3

>> B=Agent_XZ(4,5,6)

B = 

  Agent_XZ with properties:

    inventory_X: 4
    inventory_Y: 5
    inventory_Z: 6
Array = [A,B]

Error using horzcat
The following error occurred converting from Agent_XZ to Agent_XY:
Not enough input arguments.

Why the program is going to convert class of B from Agent_XZ to Agent_XY? According to the page Designing Heterogeneous Class Hierarchies, [A,B] should form an array whose class is 'Agent'. I try to verify whether the class of A or B is 'Agent', and it's true.

isa(A,'Agent')
ans =

  logical

   1

isa(B,'Agent')
ans =

  logical

   1  

I have found the shortest code to reproduce similar problem

classdef Agent < handle
end

classdef Agent_XY < Agent
end

classdef Agent_XZ < Agent
end

A=Agent_XY
A = 

  Agent_XY with no properties.

B=Agent_XZ
B = 

  Agent_XZ with no properties.

C=[A,B]
Error using horzcat
The following error occurred converting from Agent_XZ to Agent_XY:
Too many input arguments.

This time it says 'Too many input arguments.'

0 Answers0