Documentation

Create 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

Build Arrays in the Constructor

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

For example, the ObjectArray class creates an object array that is the same size as the input array. Then it initializes the Value property of each object to the corresponding input array value.

classdef ObjectArray
   properties
      Value
   end
   methods
      function obj = ObjectArray(F)
         if nargin ~= 0
            m = size(F,1);
            n = size(F,2);
            obj(m,n) = ObjectArray;
            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 ObjectArray objects.

After preallocating the array, assign each object Value property to the corresponding value in the input array F. To use the class:

  • Create 5-by-5 array of magic square numbers

  • Create a 5-by-5 object array

F = magic(5); 
A = ObjectArray(F);
whos
  Name      Size            Bytes  Class          Attributes

  A         5x5               304  ObjectArray              
  F         5x5               200  double   

Referencing Property Values in Object Arrays

Reference all values of the same property in an object array using the syntax:

objarray.PropName

For example, given the ObjProp class:

classdef ObjProp
   properties
      RegProp
   end
   methods
      function obj = ObjProp
         obj.RegProp = randi(100);
      end
   end
end

Create an array of ObjProp objects and access the RegProp property of each object:

for k = 1:5
   a(k) = ObjProp;
end
a.RegProp
ans =

    91

ans =

    13

ans =

    92

ans =

    64

ans =

    10

Related Information

For information on array initialization, see Initialize Object Arrays.

For information specific to initialization of handle array, see Initialize Arrays of Handle Objects

Was this topic helpful?