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) = obj; 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 the ObjectArray
object.
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
Given an object array objArray
in which each object has a property PropName
:
Reference the property values of specific objects using array indexing:
objArray(ix).PropName
Reference all values of the same property in an object array using dot notation. MATLAB returns a comma-separated list of property values.
objArray.PropName
To assign the comma-separated list to a variable, enclose the right-side expression in brackets:
values = [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:
for k = 1:5 objArray(k) = ObjProp; end
Access the RegProp
property of the second element of the object array using array indexing:
objArray(2).RegProp
ans = 91
Assign the values of all RegProp
properties to a numeric array:
propValues = [objArray.RegProp]
propValues = 82 91 13 92 64
Use standard indexing operations to access the values of the numeric array. For more information on numeric arrays, see Matrices and Arrays.