Effacer les filtres
Effacer les filtres

Preallocate memory for a cell of structures

5 vues (au cours des 30 derniers jours)
John
John le 10 Jan 2019
Modifié(e) : Stephen23 le 10 Jan 2019
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 commentaire
Stephen23
Stephen23 le 10 Jan 2019
Modifié(e) : Stephen23 le 10 Jan 2019
@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:

Connectez-vous pour commenter.

Réponses (1)

Guillaume
Guillaume le 10 Jan 2019
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

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Produits


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by