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

3 visualizaciones (últimos 30 días)
Dem
Dem el 5 de Jul. de 2020
Editada: Dem el 5 de Jul. de 2020
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

Respuestas (1)

Image Analyst
Image Analyst el 5 de Jul. de 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.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by