0

I would like to create an array of structure, each one of them will have 4 fields that will be an array of unspecified length.

my_struct_data.field1=a;
my_struct_data.field2=b;
my_struct_data.field3=c;
my_struct_data.field4=d;

I am planning, in fact, to insert into this array the data that will be loaded already in the struct format.

for j:1:N_data

    my_struct_data=load([my_file_name '_' j]);

    my_array_list(j)=my_struct_data;

end

What is the best way to preallocate my array of structure data?

Thank you in advance

1 Answers1

2

You can pre-allocate a few ways:

  1. Use empty cell arrays when creating the struct that are the size that you want the array of structs to be.

    mystruct = struct('field1', cell(N_data, 1), ...
                      'field2', cell(N_data, 1), ...
                      'field3', cell(N_data, 1), ...
                      'field4', cell(N_data, 1));
    
  2. Simply assign the "last" element in the struct array which will cause MATLAB to create all other structs and populate all fields with []

    mystruct(N_data, 1) = struct('field1', {'1'}, 'field2', {'2'}, ...
                                 'field3', {'3'}, 'field4', {'4'});
    
  3. Create a "default" struct and use repmat to expand it to the right size. This will make all structs have the same (non-[]) fields until changed.

    template.field1 = '1';
    template.field2 = '2';
    template.field3 = '3';
    template.field4 = '4';
    
    mystruct = repmat(template, [N_data, 1]);
    

In your specific case, one little trick you could do which is similar to #2 would be to simply invert the order of your for loop so that you populate the last element of the struct array first. This will automatically pre-allocate everything the first time through the loop.

for k = flip(1:N_data)
    my_struct_data = load([my_file_name '_' num2str(k)]);
    my_array_list(k) = my_struct_data;
end
Suever
  • 64,497
  • 14
  • 82
  • 101
  • Assigning the last array element first is an especially good approach if the fields are not known beforehand, or are nested at many levels and so are complicated to spell out. – KAE Dec 20 '19 at 17:10