I encountered the following question when writing a model where one parameter has two ‘layers’, in my case being a hierarchical grouping and a categorical explanatory variable. More specifically, the parameter is depending on the treatment (one out of 3) and the hierarchical group (one out of 5) for each data point, hence a matrix of dimension (n,m) with n=\text{number of groups}=5 and m=\text{number of treatments} = 3. Let’s assume there are 10 data points.

How can I efficiently broadcast a vector from a matrix? The example stan program below does what I want but the solution with building a big matrix and taking the diagonal is not so transparent and probably also not so efficient. I thought I could broadcast a vector from a matrix by an index being an array (of length 10) of arrays with the length 2 (the matrix dimension) encoding the group and the treatment for each data point, but I think there is no such thing like an array of arrays.

```
data {
int<lower=0> n;
int<lower=0> m;
int<lower=0> k;
matrix[n,m] a;
int<lower=0> I[k];
int<lower=0> J[k];
}
model{
}
generated quantities{
vector[k] z;
z = diagonal(a[I,J]);
}
```

```
library("rstan")
options(mc.cores = parallel::detectCores())
rstan_options(auto_write = TRUE)
a1 <- sample(1:20, 5, replace=FALSE)
a2 <- sample(1:20, 5, replace=FALSE)
a3 <- sample(1:20, 5, replace=FALSE)
data_test <- list(
n = 5,
m = 3,
k = 10,
a = t(rbind(a1,a2,a3)),
I = sample(1:5, 10, replace = TRUE),
J = sample(1:3, 10, replace = TRUE)
)
# fit
test1<-stan(
file = <the stan program just above>, # Stan program
algorithm = "Fixed_param",
data = data_test, # named list of data
chains = 1, # number of Markov chains
warmup = 0, # number of warmup iterations per chain
iter = 1, # total number of iterations per chain
)
rstan::extract(test1)
```