# Random parameter model using matrices/vectors

Hello,

I’m new in learning Stan. Now I tried to model a random parameter model using matrices and vectors.

Modeling a linear model without any heterogeneity by using matrices and vectors is clear to me:

``````data {

int<lower=0> N; //number of observations
int<lower=0> k; //number of predictors
matrix[N, k] X; //X matrix
vector[N] y; //outcome values
}
parameters {
vector [k] beta;
real<lower=0> sigma;
}

model {
y ~ normal(X*beta, sigma);
}
``````

Also modeling random parameters by specifiying each predictor by hand is clear:

``````data {

int<lower=0> N; //number of observations
int<lower=0> N_id; //number of cross-sections
int<lower=0> id[N]; //id of cross-sections
vector[N] x1; //predictor 1
vector[N] x2; //predictor 2
vector[N] y; //outcome values
}

parameters {

real alpha_0;
real beta1_0;
real beta2_0;
vector [N_id] alpha_i;
vector [N_id] beta1_i;
vector [N_id] beta2_i;
real<lower = 0> sigma_alpha;
real<lower = 0> sigma_beta1;
real<lower = 0> sigma_beta2;
real<lower = 0> sigma_y;
}

model {
alpha_i ~ normal(0, sigma_alpha);
beta1_i ~ normal(0, sigma_beta1);
beta2_i ~ normal(0, sigma_beta2);

for (i in 1:N){
y[i] ~ normal(alpha_0 + alpha_i[id[i]] + (beta1_0+beta1_i[id[i]])*x1[i] + (beta2_0+beta2_i[id[i]])*x2[i], sigma_y);
}
}
``````

But now I would like to combine using matrices and vectors with random parameters. I want to avoid having to write all of these manually for a larger number of predictors.

I tried something like the following:

``````data {

int<lower=0> N; //number of observations
int<lower=0> k; //number of predictors
int<lower=0> N_id; //number of cross-sections
int<lower=0> id[N]; //id of cross-sections
matrix[N, k] X; //X matrix
vector[N] y; //outcome values
}

parameters {

matrix [N_id, k] beta_i;
vector [k] beta;
vector<lower=0> [k] sigma_beta; // I assume non-correlated errors
real<lower = 0> sigma_y;
}

model {

}
``````

I guess everything before the model part should be ok (although I’m not really sure about the sigma_beta). But how can I code the model?

Thanks!
Dirk

I believe your concern is exactly adressed in Stan user’s guide at https://mc-stan.org/docs/2_19/stan-users-guide/linear-regression.html