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

6 views (last 30 days)
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

Answers (1)

Image Analyst
Image Analyst on 5 Jul 2020
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.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!