Indexing upper triangle


I’m looking for a way to index only the upper triangle of a matrix used in my stan model. Currently I am calculating log probabilities marginalised over a grid defined by the data, and storing the integral calculations in a matrix, of which only the upper triangle is used:

matrix[(N+1),(N+1)] lp;
  for (i in 1:N) {
    for (j in (i+1):(N+1)) {
      lp[i,j]= #operation which calculates log-likelihood

I would like to then extract only the assigned values in the matrix, which then are to be used in log_sum_exp, but I am finding this surprisingly difficult. In R this can be performed easily using lp[upper_tri(lp), however from what I can tell stan is unable to use a matrix to index.


There is no upper.tri like function in Stan, but what you have is fine.