MATLAB Object-Oriented Programming

(Joyce) #1

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 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;
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.

Initialize Arrays of Handle Objects 10-

Free download pdf