preallocate memory for a struct in a for loop

1 view (last 30 days)
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!

Accepted Answer

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

Sign in to comment.

More Answers (0)

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!