MATLAB Answers


How do I preallocate memory for a structure in MATLAB 7.6 (R2008a)?

I would like to know how to preallocate memory for a structure.

1 Answer

Answer by MathWorks Support Team on 23 Sep 2013
 Accepted answer

There is a way to preallocate memory for a structure in MATLAB 7.6 (R2008a) using the STRUCT and REPMAT commands.

EXAMPLE 1: A structure with two fields



field_names = {'field1','field2'}; % Cell with field names
empty_cells = repmat(cell(1),1,numel(field_names));
entries = {field_names{:} ; empty_cells{:}};
s = struct(entries{:}); 

EXAMPLE 2: A structure with a field with a subfield


s = struct('field1',struct('subfield',cell(1))); 

EXAMPLE 3: An array of structures




s = struct('field1',cell(1));
v = repmat(s,100,1);

Even though the data elements pointed to by the different fields in a structure are not stored contiguously, a benefit of preallocating structures is that you avoid the (possibly time-consuming) operation of dynamically growing the structure field header. Please refer to the following documentation page for more information:


Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!