MATLAB Object-Oriented Programming

(Joyce) #1

Construct Object Arrays


In this section...
“Build Arrays in the Constructor” on page 10-2
“Referencing Property Values in Object Arrays” on page 10-3

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:

10 Object Arrays

Free download pdf