MATLAB Answers

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

9 views (last 30 days)
Dem
Dem on 5 Jul 2020 at 14:03
Edited: Dem on 5 Jul 2020 at 16:42
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

  0 Comments

Sign in to comment.

Answers (1)

Image Analyst
Image Analyst on 5 Jul 2020 at 16:33
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.

  0 Comments

Sign in to comment.


Translated by