Borrar filtros
Borrar filtros

how preallocate structure for better memory

339 visualizaciones (últimos 30 días)
Salvatore Mazzarino
Salvatore Mazzarino el 22 de Sept. de 2012
Comentada: Dyuman Joshi el 27 de Mzo. de 2024
I had created a structure made so:
head.number = 3;
head.pck_rcv = [1 0 0];
heads(2).number = 5;
head(2).pck_rcv = [1 1 0];
and so on.
How can I preallocate a structure?

Respuesta aceptada

Jan
Jan el 22 de Sept. de 2012
Editada: Jan el 2 de Oct. de 2017
for k = n:-1:1 % Backwards!
head(k).number = 3;
head(k).pck_rcv = [1 0 0];
end
Now the final size of the struct array is created in the first iteration.
[EDITED] Alternatively:
head = struct('number', cell(1, 10), 'pck_rv', cell(1, 10));
Now head is a [1 x 10] struct array withe the fields 'number' and 'pck_rv'. Pre-allocating the contents of the fields is another job and you need a loop to do this. But now it can run in forward direction also.
  5 comentarios
Igor Gitelman
Igor Gitelman el 20 de Mayo de 2022
thanks! that
head = struct('number', cell(1, 10), 'pck_rv', cell(1, 10));
work fine!
Dyuman Joshi
Dyuman Joshi el 27 de Mzo. de 2024
I am accepting Jan's answer as it provides a robust solution to the question posted.

Iniciar sesión para comentar.

Más respuestas (2)

Azzi Abdelmalek
Azzi Abdelmalek el 22 de Sept. de 2012
Editada: Azzi Abdelmalek el 22 de Sept. de 2012
heads=struct('numbers',zeros(10,1), 'pck_rcv',zeros(10,3))
%then
for k=1:n
heads.numbers(k)=2
heads.pck_rcv(k,:)=[1 2 3]
end
  3 comentarios
Jan
Jan el 2 de Oct. de 2017
@Alexandra: I do not agree. Salvatore asked for a struct array: "head(2).numbers and so on". Azzi's suggestion creates a scalar struct only.
Alexandra Simpson
Alexandra Simpson el 2 de Oct. de 2017
True, I just tried it out and realised it wasn't what I wanted either! Thanks for the response.

Iniciar sesión para comentar.


Walter Roberson
Walter Roberson el 13 de Dic. de 2012
head = struct('number', {3, 5}, 'pck_rcv', {[1 0 0], [1 0 1]})

Categorías

Más información sobre Structures en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by