preallocate memory for a struct in a for loop

2 ビュー (過去 30 日間)
jason lee
jason lee 2020 年 7 月 2 日
コメント済み: Walter Roberson 2020 年 7 月 2 日
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 Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by