필터 지우기
필터 지우기

Preallocate memory for a cell of structures

조회 수: 5 (최근 30일)
John
John 2019년 1월 10일
편집: Stephen23 2019년 1월 10일
What is the correct syntax to preallocate memory for the cell x in the following?
N = 10;
for n = 1:N
numRows = ceil(100*rand);
x{n}.field1 = 1*ones(numRows,1);
x{n}.field2 = 2*ones(numRows,1);
x{n}.field3 = 3*ones(numRows,1);
end
  댓글 수: 1
Stephen23
Stephen23 2019년 1월 10일
편집: Stephen23 2019년 1월 10일
@John: is there a specific requirement to use a cell array of structures? From the code that you have shown, a single non-scalar structure would likely be a better choice:

댓글을 달려면 로그인하십시오.

답변 (1개)

Guillaume
Guillaume 2019년 1월 10일
Just preallocating the cell array:
x = cell(1, N);
for ...
There wouldn't be much point preallocating the scalar structures inside each cell, particularly if you did it naively using repmat as they would be shared copy which would need deduplicating at each step of the loop. You could preallocate the structures inside the loop. For a structure with 3 fields, there wouldn't be much benefit:
x = cell(1, N);
for n = 1:N
x{n} = struct('field1', [], 'field2', [], 'field3', [])
x{n}.field1 = ...
end
But you may as well fill the structure directly with:
x = cell(1, N);
for n = 1:N
numRows = ceil(100*rand);
x{n} = struct('field1', 1*ones(numRows,1), 'field2', 2*ones(numRows,1), 'field3', 3*ones(numRows,1))
end
However, instead of a cell array of scalar structures you would be better off using a structure array:
x = struct('field1', cell(1, N), 'field2', [], 'field3', []) %creates a 1xN structure with 3 empty fields
for n = 1:N
x(n).field1 = ...
x(n).field2 = ...
x(n).field3 = ...
end

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

태그

제품


릴리스

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by