This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English verison of the page.

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.

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
      function obj = InitHandleArray
         obj.RandNumb = randi(100);

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

Consider what happens when MATLAB initialize 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;
ans =


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:

ans =


MATLAB copies this second instance to all remaining array elements:

ans =

ans =


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 =


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

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

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

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

Was this topic helpful?