0

我有一个自定义类ClassA,我想创建一个空对象数组N来存储N ClassA对象。

现在我正在使用一个空单元格数组cellarrayA = cell(N,1),并将每个对象放入单元格中,例如cellarrayA(n) = ClassA(input(n)). 完成后,我使用 . 将单元格数组转换为对象数组objarrayA = [cellarrayA{:}]

它可以工作(Matlab 没有抱怨),但我认为它实际上并没有预先分配正确的内存量,因为元胞数组如何在创建对象之前知道我的对象的大小?我的对象的大小可能相当大,大约为 1MB(但可能会有所不同)。我想我可能会遭受同样的性能损失,就像我根本没有预分配任何东西一样,尽管我无法验证它。那么如何预先分配对象数组,而不是使用元胞数组呢?

4

1 回答 1

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.

于 2018-01-25T21:03:35.250 回答