Documentation Center

  • Trial Software
  • Product Updates

Creating Object Arrays

Basic Knowledge

The material presented in this section builds on an understanding of the information presented in the following sections.

 Class Definitions

 Working with Arrays

Building Arrays in the Constructor

A constructor method can create an object array by building the array and returning it as the output argument.

For example, the following DocArrayExample class creates an object array the same size as the input array and initializes the Value property of each object to the corresponding input array value.

classdef DocArrayExample
   properties
      Value
   end
   methods
      function obj = DocArrayExample(F)
         if nargin ~= 0 % Allow nargin == 0 syntax
            m = size(F,1);
            n = size(F,2);
            obj(m,n) = DocArrayExample; % Preallocate object array
            for i = 1:m
               for j = 1:n
                  obj(i,j).Value = F(i,j);
               end
            end
         end
      end
   end
end

To preallocate the object array, assign the last element of the array first. MATLAB® fills the first to penultimate array elements with default DocArrayExample objects.

After preallocating the array, assign each object Value property to the corresponding value in the input array F. For example:

F = magic(5);  % Create 5-by-5 array of magic square numbers
A = DocArrayExample(F); % Create 5-by-5 array of objects

Initializing Arrays of Value Objects

During the creation of object arrays, MATLAB might need to call the class constructor with no arguments, even if the constructor does not build an object array. For example, suppose you define the following class:

classdef SimpleClass
   properties
      Value
   end
   methods
      function obj = SimpleClass(v)
         obj.Value = v;
      end
   end
end

Now execute the following statement (which is a valid MATLAB statement):

a(1,7) = SimpleClass(7)
Error using SimpleClass>SimpleClass.SimpleClass
Not enough input arguments.

This error occurs because MATLAB calls the constructor with no arguments to initialize elements 1 through 6 in the array (that is, a(1,1:6)).

Therefore, you must ensure the constructor supports the no input argument syntax. A simple solution is to test nargin and let the case when nargin == 0 execute no code, but not error:

classdef SimpleClass
   properties
      Value
   end
   methods
      function obj = SimpleClass(v)
         if nargin > 0
            obj.Value = v;
         end
      end
   end
end

Using the revised class definition, the previous array assignment statement executes without error:

a(1,7) = SimpleClass(7)
a = 
  1x7 SimpleClass array with properties:

    Value

The object assigned to array element a(1,7) uses the input argument passed to the constructor as the value assigned to the property:

a(1,7)
ans = 
  SimpleClass with properties:

    Value: 7

However, MATLAB created the objects contained in elements a(1,1:6) with no input argument and initialized the value of the Value property to empty []. For example:

a(1,1)
ans = 
  SimpleClass with properties:

    Value: []

MATLAB calls the SimpleClass constructor once and copies the returned object to each element of the array.

Initial Value of Object Properties

When MATLAB calls a constructor with no arguments to initialize an object array, one of the following assignments occurs:

  • If property definitions specify default values, MATLAB assigns these values.

  • If the constructor assigns values in the absence of input arguments, MATLAB assigns these values.

  • If neither of the above situations apply, MATLAB assigns the value of empty double (i.e., []) to the property.

Creating Empty Arrays

Empty arrays have no elements, but are of a certain class. All nonabstract classes have a static method named empty that creates an empty array of the same class. The empty method enables you to specify the dimensions of the output array. However, at least one of the dimensions must be 0. For example:

ary = SimpleClass.empty(5,0);

creates a 5–by–0 empty array of class SimpleClass.

Calling empty with no arguments returns a 0–by–0 empty array.

Assigning Values to an Empty Array

An empty object defines the class of an array. However, to assign nonempty objects to an empty array, MATLAB must call the class constructor to create default instances of the class for every other array element. Once you assign a nonempty object to an array, all array elements must be nonempty objects.

    Note:   A class constructor should never return empty objects by default.

For example, using the SimpleClass defined in the Initializing Arrays of Value Objects section, create an empty array:

ary = SimpleClass.empty(5,0);
class(ary)

ans =

SimpleClass

The array ary is an array of class SimpleClass. However, it is an empty array:

ary(1)
Index exceeds matrix dimensions.

If you make an assignment to a property value, MATLAB calls the SimpleClass constructor to grow the array to the require size:

ary(5).Value = 7;
ary(5).Value

ans = 

    7

ary(1).Value

ans = 

    []

In this case, MATLAB populates array elements one through five with SimpleClass objects created by calling the class constructor with no arguments. Then MATLAB assigns the property value 7 to the object at ary(5).

Initializing Arrays of Handle Objects

When MATLAB expands an array, it calls the class constructor once, and then creates unique handles for each element in the array. MATLAB copies the property values from the constructed object without calling the constructor for each additional element.

The following class illustrates this behavior.

classdef InitArray < handle
   properties
      RandNumb
   end
   methods
      function obj = InitArray
         obj.RandNumb = randi(100);
      end
   end
end

The property RandNumb contains a random number that is assigned from the InitArray class constructor. The next section uses the InitArray class to show when MATLAB calls the class constructor when expanding an array.

Initializing a Handle Object Array

Consider what happens when MATLAB initialize an array by first assigning to the last element in the array. (The last element is the one with the highest index values). For example, suppose the value of the RandNumb property of the InitArray object assigned to the element A(4,5) is 59:

A(4,5) = InitArray;
A(4,5).RandNumb

ans =

     59

The element in the index location A(4,5) is an instance of the InitArray class. Element A(1,1) is also an instance of the InitArray class, but its RandNumb property is set to a different random number. The difference is caused by the fact that MATLAB called the class constructor to create a single object, which MATLAB then copied to all the remaining array elements. Calling the constructor resulted in another call to the randi function, which returns a new random number:

A(1,1).RandNumb

ans =

     91

MATLAB copies this second instance to all remaining array elements:

A(2,2).RandNumb

ans =

     91

A(2,3).RandNumb

ans =

    91

When initializing an object array, MATLAB assigns a copy of a single object to the empty elements in the array. However, MATLAB gives each object a unique handle so that later you can assign different property values to each object. This means that the objects are not equivalent:

A(1,1) == A(2,2)
ans =

     0

Therefore, the creation of an array with a statement such as:

A(4,5) = InitArray;

results in two calls to the class constructor. The first creates the object for array element A(4,5). The second creates a default object (no arguments passed to the constructor) that MATLAB copies to all remaining empty array elements.

See Indexing Multidimensional Arrays and Reshaping Multidimensional Arrays for information on array manipulation.

See Initializing Properties to Unique Values for information on assigning values to properties.

See Indexed Reference and Assignment for information on implementing subsasgn methods for your class.

Referencing Property Values in Object Arrays

You can reference all values of the same property in an object array using the syntax:

objarray.PropName

For example, given the ObjArray class:

classdef ObjArray 
   properties
      RegProp
   end
   methods
      function obj = ObjArray
         % Assign property a random integer
         obj.RegProp = randi(100);
      end
   end
end

Create an array of ObjArray objects and assign all values of the RegProp property to the propvalues cell array:

for k = 1:5
   a(k) = ObjArray;
end
propvalues = {a.RegProp}

propvalues = 

    [96]    [49]    [81]    [15]    [43]

Object Arrays with Dynamic Properties

See Dynamic Properties — Adding Properties to an Instance for information about classes that can define dynamic properties.

You cannot reference all the dynamic properties in an object array using a single statement, as shown in the previous section for ordinary properties. For example, suppose the ObjArray class subclasses the dynamicprops class, which enables you to add properties to instances of the ObjArray class.

classdef ObjArray < dynamicprops
   properties
      RegProp
   end
   methods
      function obj = ObjArray
         % Assign property a random integer
         obj.RegProp = randi(100);
      end
   end
end

Create an object array and add dynamic properties to each member of the array:

% Define elements 1 and 2 as ObjArray objects
a(1) = ObjArray;
a(2) = ObjArray;
% Add dynamic properties to each object and assign a value
a(1).addprop('DynoProp');
a(1).DynoProp = 1;
a(2).addprop('DynoProp');
a(2).DynoProp = 2;

You can get the values of the ordinary properties, as with any array:

a.RegProp

ans =

     4

ans =

    85

MATLAB returns an error if you try to access the dynamic properties of all array elements using this syntax.

a.DynoProp
No appropriate method, property, or field DynoProp for class ObjArray.

You must refer to each object individually to access dynamic property values:

a(1).DynoProp

ans =

     1
a(2).DynoProp

ans =

     2
Was this topic helpful?