Preallocate memory for a cell of structures
6 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
回答 (1 件)
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
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!