Josh
Josh

Reputation: 1429

Preallocating arrays of structures in Matlab for efficiency

In Matlab I wish to preallocate a 1x30 array of structures named P with the following structure fields:

           imageSize: [128 128]
orientationsPerScale: [8 8 8 8]
        numberBlocks: 4
          fc_prefilt: 4
   boundaryExtension: 32
                   G: [192x192x32 double]

G might not necessarily be 192x192x32, it could be 128x128x16 for example (though it will have 3 dimensions of type double).

I am doing the preallocation the following way:

P(30) = struct('imageSize', 0, 'orientationsPerScale', [0 0 0 0], ...
'numberBlocks', 0, 'fc_prefilt', 0, 'boundaryExtension', 0, 'G', []);

Is this the correct way of preallocating such a structure, or will there be performance issues relating to G being set to empty []? If there is a better way of allocating this structure please provide an example.

Also, the above approach seems to work (performance issues aside), however, the order of the field name / value pairs seems to be important, since rearranging them leads to error upon assignment after preallocation. Why is this so given that the items/values are referenced by name (not position)?

Upvotes: 1

Views: 475

Answers (1)

Emilio M Bumachar
Emilio M Bumachar

Reputation: 2613

If G is set to Empty, the interpreter has no way of knowing what size data will be attributed to it later, so it probably will pack the array items tight in memory, and have to redo it all when it doesn't fit.

It's probably more efficient to define upper bounds for the dimensions of G beforehand, and set it to that size. The zeroes function could help.

Upvotes: 1

Related Questions