MATLAB Object-Oriented Programming

(Joyce) #1

Initialize Object Arrays


In this section...
“Calls to Constructor” on page 10-5
“Initial Value of Object Properties” on page 10-6

Calls to Constructor


During the creation of object arrays, MATLAB can call the class constructor with no
arguments, even if the constructor does not build an object array. For example, suppose
that you define the following class:

classdef SimpleValue
properties
Value
end
methods
function obj = SimpleValue(v)
obj.Value = v;
end
end
end

Execute the following statement to create an array:

a(1,7) = SimpleValue(7)

Error using SimpleValue (line 7)
Not enough input arguments.

This error occurs because MATLAB calls the constructor with no arguments to initialize
elements 1 through 6 in the array.

Your class must support the no input argument constructor syntax. A simple solution is to
test nargin and let the case when nargin == 0 execute no code, but not error:

classdef SimpleValue
properties
Value
end
methods
function obj = SimpleValue(v)

Initialize Object Arrays
Free download pdf