Azzera filtri
Azzera filtri

Preallocate memory for a cell of structures

5 visualizzazioni (ultimi 30 giorni)
John
John il 10 Gen 2019
Modificato: Stephen23 il 10 Gen 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 Commento
Stephen23
Stephen23 il 10 Gen 2019
Modificato: Stephen23 il 10 Gen 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:

Accedi per commentare.

Risposte (1)

Guillaume
Guillaume il 10 Gen 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

Categorie

Scopri di più su Structures in Help Center e File Exchange

Prodotti


Release

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by