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.

chappjc
  • 30,359
  • 6
  • 75
  • 132
Nitin
  • 2,624
  • 7
  • 29
  • 43

1 Answers1

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();
  • 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. – Nitin Apr 20 '13 at 20:34
  • 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. –  Apr 20 '13 at 20:49