Main Content

Initialize Arrays of Handle Objects

When initializing an array of handle objects, MATLAB® fills in the empty elements of an array with a default object. To create the default object, MATLAB:

  • Calls the class constructor once to obtain an object

  • Creates unique handles for each element in the array

  • Copies the property values from the constructed default object without calling the constructor again.

The InitHandleArray class illustrates this behavior.

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

The property RandNumb contains a random number that the InitHandleArray constructor assigns.

Consider what happens when MATLAB initializes an array created by assigning to the last element in the array. (The last element is the one with the highest index values). Suppose the value of the RandNumb property of the InitHandleArray object assigned to the element A(4,5) is 59:

A(4,5) = InitHandleArray;
A(4,5).RandNumb
ans =

     59

The element in the index location A(4,5) is an instance of the InitHandleArray class. The default object used for element A(1,1) is also an instance of the InitHandleArray class, but its RandNumb property is set to a different random number.

To fill in the preceding array elements, MATLAB calls the class constructor to create a single object. MATLAB copies this object to all the remaining array elements. Calling the constructor to create the default object resulted in another call to the randi function, which returns a new random number:

A(1,1).RandNumb
ans =

     10

MATLAB copies this second instance to all remaining array elements:

A(2,2).RandNumb
ans =

     10
A(2,3).RandNumb
ans =

    10

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

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

     0

That is, the handle A(1,1) does not refer to the same object as A(2,2). The creation of an array with a statement such as:

A(4,5) = InitHandleArray;

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 that MATLAB copies to all remaining empty array elements.

Related Information

For information on array manipulation, see Multidimensional Arrays

See Handle Objects as Default Property Values for information on assigning values to properties.

See Customize Object Indexing for information on implementing subsasgn methods for your class.