How do I preallocate memory for a structure in MATLAB 7.6 (R2008a)?
조회 수: 4 (최근 30일)
이전 댓글 표시
MathWorks Support Team
2013년 9월 23일
편집: MathWorks Support Team
2021년 12월 13일
I would like to know how to preallocate memory for a structure.
채택된 답변
MathWorks Support Team
2021년 12월 10일
편집: MathWorks Support Team
2021년 12월 13일
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
s.field1
s.field2
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.field1.subfield
s = struct('field1',struct('subfield',cell(1)));
EXAMPLE 3: An array of structures
v(1).field1
...
v(100).field1
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:
댓글 수: 1
Walter Roberson
2017년 2월 15일
The line
empty_cells = repmat(cell(1),1,numel(field_names));
creates a cell array of copies of [] . The line
entries = {field_names{:} ; empty_cells{:}};
arranges those copies below the field names, like
{ 'first', 'second', 'third';
[], [], [] }
and the line
s = struct(entries{:});
converts that to
a = struct('first', [], 'second', [], 'third', [])
so already [] is being used.
The code given in the first part of the solution is code to automatically generate this just given the field names.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!