preallocate memory for a struct in a for loop
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
jason lee
el 2 de Jul. de 2020
Comentada: Walter Roberson
el 2 de Jul. de 2020
here is my code:
for i = 1:size(filename,1)
spectra(i).name = filename(i,1:end-4);
spectra(i).value = readmatrix(filename(i,:));
end
save spectra.mat spectra
MATLAB suggests to preallocate memory for struct spectra.
i am wondering how to do it.
Thank you!
0 comentarios
Respuesta aceptada
Walter Roberson
el 2 de Jul. de 2020
for i = size(filename,1) : -1 : 1
spectra(i).name = filename(i,1:end-4);
spectra(i).value = readmatrix(filename(i,:));
end
save spectra.mat spectra
2 comentarios
Walter Roberson
el 2 de Jul. de 2020
MATLAB only needs to extend an array dynamically if you write past the existing end of the array. One way to not have to write past the end (triggering a resize) is to write from the end backwards to the beginning: the very first assignment makes it the maximum size, and then you go backwards filling in what was missed.
Note: this will not work exactly like you might expect if the array already exists when you do this. If you for some reason had another for loop around all of this, then the next time through, the number of filenames might be less, and you would probably not want the array left at "the biggest size it has ever been" (though that can be useful sometimes.) One way to deal with this is that after the above loop, you could do
spectra(size(filenamne,1)+1:end) = [];
which would erase any entries past what you used this time.
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!