Thursday, February 14, 2013

Pre-allocating an array of objects of a structure array in Matlab

I often run into the issue of how to pre-allocate a structure or array before populating it inside a loop in Matlab. This discussion at Stack Overflow, along with some other internet searches, provided the answer:
For objects the pre-allocation works by assigning one of the objects to the very last field in the array. Matlab then fills the other fields before that with objects (handles) that it creates by calling the constructor of that object with no arguments (see Matlab help)
So if I want to create a structure array with one hundred elements and two fields (called xCoord and yCoord), I would enter

myStruct(100).xCoord = 0;
myStruct(100).yCoord = 0;
 and then proceed to populate all the previous elements of myStruct.