preallocate memory for a struct in a for loop

4 次查看(过去 30 天)
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!

采纳的回答

Walter Roberson
Walter Roberson 2020-7-2
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 个评论
jason lee
jason lee 2020-7-2
yes, it really works!
but why?
could you please make some comments?
Walter Roberson
Walter Roberson 2020-7-2
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by