Normally, this is what I do in order to achieve class array "preallocation":
1) I define a constructor in my class that accepts no input arguments, as follows:
classdef MyClass
properties
MyProperty
end
methods
function obj = MyClass()
% ...
end
end
end
2) I use the repmat function in order to instantiate an array of MyClass
instances:
classes = repmat(MyClass(),10,1);
3) If necessary, I loop over the array initializing the properties of instance with the proper values:
A = [ ... ]; % 10-by-1 matrix with numerical values
for i = 1:numel(classes)
classes(i).MyProperty = A(i);
end
If every instance can be initialized with the same default property values, I use the approach in Step 2 calling a constructor that is able to assign them properly instead:
classes = repmat(MyClass('default_property_value'),10,1);
You should by no means use this approach if your MyClass
inherits from the handle
class:
classdef MyClass < handle
% ...
end
otherwise the process will produce an array of copies of the same handle. Also, this method must not be intended as a true memory preallocation process, since it works by replicating a copy of a single allocated instance of the class over and over. For sure, this will make Matlab stop crying about a missing preallocation, if this is your main concern. And for sure this will retun an array of objects.