2

In Matlab, I have a class named "point" (which is not a handle class).

I use a loop that creates a cell array of points, making it grow at each iteration without preallocation:

    for k=1:npoints
      newpoint=point(*some parameters that depend on k*);
      pointcell{k}=newpoint; % pointcell grows at each iteration
    end

In this example, the cell array "pointcell" grows at each iteration, which may not be optimal in terms of performance. Is it useful to preallocate this cell array, and if yes how can this be done ? Just using pointcell=cell(npoints) doesn't seem to work..

Oli
  • 15,935
  • 7
  • 50
  • 66
calvin tiger
  • 391
  • 2
  • 7
  • 18

3 Answers3

2

Also consider to use array of objects, instead of cell array of objects.

When you allocate a cell array, you aren't really helping Matlab to manage the memory. That is because each cell can be of any size, thus the only thing that can be preallocated is an array of pointers. Check out this for more info on cell arrays.

And then you can allocate an array of objects by doing repmat

points = repmat(point(defaultVal1,defaultVal2,...),1,npoints);
for k=1:npoints
    newpoint=point(*some parameters that depend on k*);
    points(k)=newpoint; % pointcell grows at each iteration
end
Community
  • 1
  • 1
Andrey Rubshtein
  • 20,795
  • 11
  • 69
  • 104
0

The recommended way to pre-allocate a cell array is one of:

pointcell = cell(npoints);

or

pointcell = {};
pointcell{1, npoints} = [];
nibot
  • 14,428
  • 8
  • 54
  • 58
0
pointcell = cell(npoints, 1);

I recommend sticking with your cell-array approach. One of the other answers mentioned using an array of objects; I do NOT recommend doing that! Assignment into a pre-allocated cell array is fast, where assignment into an array of objects is comparatively very slow. I think you have the right approach already.

siliconwafer
  • 732
  • 4
  • 9