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 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