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!