Empty Arrays
Creating Empty Arrays
Empty arrays have no elements, but are of a certain class. All nonabstract classes have a static method named empty
that creates an empty array of the same class. The empty
method enables you to specify the dimensions of the output array. However, at least one of the dimensions must be 0
. For example, define the SimpleValue
class:
classdef SimpleValue properties Value end methods function obj = SimpleValue(v) if nargin > 0 obj.Value = v; end end end end
Create a 5–by–0 empty array of class SimpleValue
.
ary = SimpleValue.empty(5,0)
ary = 5x0 SimpleValue array with properties: Value
Calling empty
with no arguments returns a 0–by–0 empty array.
Assigning Values to an Empty Array
An empty object defines the class of an array. To assign nonempty objects to an empty array, MATLAB® calls the class constructor to create default instances of the class for every other array element. Once you assign a nonempty object to an array, all array elements must be nonempty objects.
Note
A class constructor must avoid returning empty objects by default.
For example, using the SimpleValue
defined in the Initialize Object Arrays section, create an empty array:
ary = SimpleValue.empty(5,0); class(ary)
ans = SimpleValue
ary
is an array of class SimpleValue
. However, it is an empty array:
ary(1)
Index exceeds matrix dimensions.
If you make an assignment to a property value, MATLAB calls the SimpleClass
constructor to grow the array to the require size:
ary(5).Value = 7; ary(5).Value
ans = 7
ary(1).Value
ans = []
MATLAB populates array elements one through five with SimpleValue
objects created by calling the class constructor with no arguments. Then MATLAB assigns the property value 7
to the object at ary(5)
.