How do I pre-allocate a struct in a while loop with unknown N?

조회 수: 6 (최근 30일)
Dem
Dem 2020년 7월 5일
편집: Dem 2020년 7월 5일
Hello, can anyone help me to understand how can i pre-allocate the output that I get in "statuses" (statuses is a Nx1 cell, where each cell is 1x1 struct) in order to increase the efficency of the code?
The code is working and it is not mine(i took it from matlab documentation), I just would like to understand how to solve the problem).
Thanks a lot.
tweetquery = 'hello';
s = search(c,tweetquery,'count',100);
statuses = s.Body.Data.statuses;
%
while isfield(s.Body.Data.search_metadata,'next_results')
nextresults = string(s.Body.Data.search_metadata.next_results);
max_id = extractBetween(nextresults,"max_id=","&");
cmax_id = char(max_id);
s = search(c,tweetquery,'count',100,'max_id',cmax_id);
statuses = [statuses;s.Body.Data.statuses];
end

답변 (1개)

Image Analyst
Image Analyst 2020년 7월 5일
You could preallocate a huge amount -- way more than you think you'd need -- then just use indexing after the loop to crop it to the actual number of loop iterations that were performed. You'd need to set up a loop counter that you increment by one on each iteration.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by