Do not output a variable from generated quantities

Is there a way to prevent a variable in “generated quantities” block from being added to the output? For example, in the following code, I do not need mu in the output, I only need log_lik.

generated quantities{
    vector[n] log_lik;
    real mu; // <----- I do not want this in the output

    for (i in 1:n) {
        mu = a + b * speed[i];
        log_lik[i] = normal_lpdf(dist[i] | mu, sigma);
    }
}

Any variables that are declared inside a loop (or inside brackets) won’t be saved. Either of the following two examples should achieve what you want:

generated quantities{
    vector[n] log_lik;

    for (i in 1:n) {
        real mu = a + b * speed[i];
        log_lik[i] = normal_lpdf(dist[i] | mu, sigma);
    }
}

or

generated quantities{
    vector[n] log_lik;

    {
        real mu;
        for (i in 1:n) {
            mu = a + b * speed[i];
            log_lik[i] = normal_lpdf(dist[i] | mu, sigma);
        }
    }
}
4 Likes

Thanks, it works! It would be great to have this information in the manual.

1 Like

It could be a bit more verbose.

2 Likes

That’s a very good doc thanks. It will also be great to write something like this in generated quantities doc, because I had no idea which variables are printed out lol:

All variables declared in the outer scope of generated quantities block are printed as part of the output. To avoid printing out a temporary variable, declare it inside inner curly brackets or other blocks (i.e. if-statements, loops), for example:

generated quantities{
    int a; // added to the output

    {
        int b; // not added to the output
    }
}

2 Likes

Thanks @Evgenii, I’ve opened a pull request to amend the manual in the spirit of your suggestion: https://github.com/stan-dev/docs/pull/153

2 Likes