Documentation

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.

Construct Object 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

Assign the property values to a numeric array:

PropArray = [a.RegProp]
PropArray =

    82    91    13    92    64
size(PropArray)
ans =

     1     5

Index the array to access specific values. For example, to access the second array element, use,

PropArray(2)
ans =

    91

Related Examples

Was this topic helpful?