matlabdata-structurespre-allocation

How to pre-allocate a structure vector in Matlab


In matlab, the function struct allow to pre-allocate a structure like this

S = struct(field1,{},field2,{},...,fieldN,{})

But I need S to be a vector of structures of let's say a length of 100, and I don't know how to do that. I want to do this so that later I can assign

S(60).field1=1234;

Without making S to change size as a consequence of the assignment.


Solution

  • You have to specify the size of S trough the size of the values you assign to each field during the creation of the structure. In this case the following line would do the trick

    S = struct(field1,cell(1,100),field2,cell(1,100),...,fieldN,cell(1,100));
    

    As pointed out by Cris Luengo in the comments, you can also use a scalar for all but one field. Therefore, the following line would have the exact same result

    S = struct(field1,cell(1,100),field2,[],...,fieldN,[]);