Lorenzo Meneghetti
Lorenzo Meneghetti

Reputation: 134

MATLAB: how to allocate an array of structure data

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

Upvotes: 0

Views: 1211

Answers (1)

Suever
Suever

Reputation: 65430

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

Upvotes: 2

Related Questions