Initializing array to zero

Hey all,

just wondering if there is a builtin function for initializing matrices (or vectors) to 0 (or 1). Based on the comment here, matrices are initialized to NaNs. It would be useful to have a function for setting all elements to 0 rather than writing a for loop every time. I couldn’t find anything for this in the docs.

thanks

1 Like

rep_vector and rep_matrix

1 Like

Apologies for resuming an old thread, but the title describes exactly what I’m looking for. You can initialize vector and matrices using rep_vector and rep_matrix. Is there a way to initialize arrays in a similar way?

At the moment I do something like the below:

transformed parameters {
    real<lower=0> total_revenue[n_variants];
    real<lower=0> total_orders[n_variants];
    real<lower=0> aov[n_variants];

    for (v in 1:n_variants) {
        total_revenue[v] = 0;
        total_orders[v] = 0;
    }

    for (n in 1:N) {
        total_revenue[variant[n]] += revenue[n];
        total_orders[variant[n]] += orders[n];
    }
    for (v in 1:n_variants) {
        aov[v] = total_revenue[v] / total_orders[v];
    }
}

I wonder if there was a cleaner solution that would avoid that ugly first for-loop :-)

1 Like

yes, there’s a rep_array function as well. see the Stan reference manual for details.

1 Like

Whoops, that was a stupid question. I should have searched for that first in the manual. Thanks @mitzimorris