Dynamically updating (and growing) array/vector


I’m trying to do something where I need to compute log_sum_exp on a vector/array of varying size. The following code compiles fine:

functions {
 real do_something(int i, real lambda){
   return( poisson_lpmf(i | lambda) );
 real sum_until_condition(real lambda){
   real lprob;
   vector[1] store;
   int counter = 0;
   store[1] = do_something(1, lambda);
   while(counter < 10){
     counter += 1;
     print("Doing iteration ", counter);
     store = append_row(store, do_something(counter, lambda));
   lprob = log_sum_exp(store);

but when run gives me
assign: Rows of left-hand-side (1) and rows of right-hand-side (2) must match in size, which I guess is trying to tell me that Stan needs the object store to have rows(store) = 1 because that’s what was defined. Is there anyway I can get an array or vector of variable size, when I don’t know what the size should be ahead of time? I could make store an array of size 1000000 or whatever and only log_sum_exp over the appropriate indices, but I reckon that could lead to bad memory usage. Is this fear justified? If yes, is there anything I can do to bypass creating a ginormous array/vector?

Basically, no. But the log_sum_exp of a vector can be written as the log_sum_exp of the first two elements of the vector, log_sum_exped with the third element, log_sum_exp'ed with the fourth element, … . There is something similar in

1 Like