# Transform a matrix of parameter to a vector of parameter in Stan

Hi,

I am wondering whether we could create an empty vector in Stan and add multiple elements to it based on some criteria (like creating a vector beta_selected = c() and assign elements to it in R). For example, in the below Stan code, I would like to construct a vector of parameters of length N (beta_selected) based on a matrix of parameters (beta) in my model. The selection criteria are as follows: We have a known matrix A matching the dimension of matrix beta, and elements in A are either 0 or 1. We loop through all the columns i and rows j of A, and if A[i,j] = 1 we attach the parameter beta[i,j] to beta_selected and if A[i,j] = 0 we do nothing to beta_selected. May I ask that how could I implement such processes in Stan?

``````data {
int<lower= 1> N; // N < 36
matrix[6, 6] A;
}
parameter {
matrix[6, 6] beta;
}
transformed parameter {
vector[N] beta_selected;
}
``````

Thanks so much for your help!

Something like this should do what you’re after:

``````data {
int<lower= 1> N; // N < 36
matrix[6, 6] A;
}
parameters {
matrix[6, 6] beta;
}
transformed parameters {
vector[N] beta_selected;
{
int i = 1;  // Track index of beta_selected to assign to
for(r in 1:rows(A)) {
for(c in 1:cols(A)) {
if(A[r,c] == 1) {
beta_selected[i] = beta[r,c];
i += 1;
}
}
}
}
}
``````