Base type mismatch when trying to simplify explanatory variable and coefficient code

Given the increasing complexity of my model, I’m trying to condense the code using vectors and matrices. As a result though I’m running into some base type mismatch problems that I can’t solve.

Say you have the following code as part of your model, I’ve tried to strip out unnecessary info:

data {
  int<lower=1> N; //data points
  real Y[N]; //dependent variable
  int Nx; //number of predictors
  matrix[N,Nx] XVar; //matrix of explanatory variable values
parameters {
  vector[Nx] beta_mu; //Mu parameters for Xvar, assume no intercept
model {
  to_vector(beta_mu) ~ normal(0,1); //priors
  //linear predictor
  real mu[N];
  for (i in 1:N) {
     mu[i] = beta_mu * XVar[i,];

The problem occurs during the likelihood where I get a “Base type mismatch in assignment”, as it complains that ‘mu’ is not a matrix (which is understandable). Is there a way to succinctly sum out the beta_mu * XVar[i,] expression without having to index out every coefficient and the corresponding matrix column?

vector[N] mu = Xvar * beta_mu;

Also, beta_mu is already a vector so to_vector(beta_mu) is just a needless copy

1 Like

Thanks Ben, unfortunately my initial oversimplification of the model means I still can’t get to a solution.

My model is hierarchical (with just random intercepts) so I feel like I need to loop over the linear predictor such that:

  for (i in 1:N) {
     mu[i] = group_int[grlookup[i]] + beta_mu * XVar[i,];

Given this, would something like sum(beta_mu * XVar[i,]) work?

Thanks for the point on to_vector.

vector[N] mu = group_int[grlookup] + XVar * beta_mu;

1 Like