1

I am trying to create an array of objects of a class Cell in another class Systemin MATLAB. The classCell` is:

classdef Cell
 properties
    ID;
    EntityID;
    ZoneID;
    NeighborID; 
    State;
    nextChangeTime;
 end

 methods
 % Define the constructor
    function obj = Cell()
        obj.ID = zeros(1);
        obj.EntityID = zeros(1);
        obj.ZoneID = zeros(1);
        obj.NeighborID = zeros(1); 
        obj.State = zeros(1);
        obj.nextChangeTime = zeros(1);
    end
 end

Now I have another class System. I try to make an array of Cell objects like this:

classdef System
  properties
    Cells;
  end

  methods
    function obj = System(dimx,dimy)
      obj.Cells(dimx,dimy) = Cell();
    end
  end

But I think I am using the wrong format. Not sure if this is possible. Any suggestions on how to accomplish this would be appreciated.

1 Answer 1

2

In order to be able to create arrays of objects of user-defined class (e.g. Cell class), it is convenient to have the default constructor for the user-defined class. The default constructor is the one that takes no arguments (i.e. when nargin==0). When creating arrays, the implicit initialization of the array's objects is done by this constructor. If this constructor is missing, trying to build arrays by "extending" a scalar object will generate an error.

Another way of creating arrays of objects (without defining a default constructor) is by using horzcat, vertcat and cat.

Aaaaand... when accessing the properties of an object, don't forget to mention the object you're accessing:

obj.Cells = Cell.empty(0,0);  % Force the type of empty Cells to Cell class
obj.Cells(dimx,dimy) = Cell();
Sign up to request clarification or add additional context in comments.

2 Comments

So I have a default constructor for Cell defined. But when I try to execute the statement obj.Cells(dimx,dimy) = Cell(); it says Conversion to double from Cell is not possible.
I adjusted the code, please take a look into my post again. Apparently the default type for an empty property is double. We need to change it to Cell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.