0

I have a self defined class ClassA, and I want to create an empty object array of size N to store N ClassA objects.

Right now I am using an empty cell array cellarrayA = cell(N,1), and putting each object into the cell, like cellarrayA(n) = ClassA(input(n)). And once they're all done I turn the cell array into object array using objarrayA = [cellarrayA{:}].

It works (Matlab does not complain) but I don't think it actually preallocate the right amount of memory, because how can a cell array know the size of my object before it's created? The size of my object could be fairly large, on the order of 1MB (but it could vary). I would guess I might be suffering the same performance penalty just as if I'm not preallocating anything at all, although I won't be able to verify it. So how can I preallocate the object array, instead of using the cell array?

LWZ
  • 11,670
  • 22
  • 61
  • 79
  • Pre-allocation is not so explicit in Matlab as other languages, if you want a `NxM ClassA` object then you can implement that within the class. Memory management wise it will be no better though unless your empty class of size `NxM` allocates storage for each element. At that stage you're potentially making your class array bloated before populating it, rather than streamlining memory – Wolfie Jan 25 '18 at 18:36

1 Answers1

0

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.

Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98