Nan at the initial value

I generated data with this model

data {
  int<lower=0> N;
  int<lower=1> K;
}
generated quantities {
  real x[N];
  real u[N];
  for (n in 1:N) {
    x[n] = normal_rng(0,1);
    u[n] = normal_rng(0,1);
  }
  real beta[K];
  real gamma[K];
  for (k in 1:K) {
      beta[k] = normal_rng(1,1);
      gamma[k] = normal_rng(3,1);
  }
  real<lower=0> sigma = uniform_rng(.6,.8);
  real mu[N];
  real y[N];
  simplex[K] theta;
  int<lower=1,upper=K> kk[N];
  theta = dirichlet_rng(rep_vector(1,K));
  for (n in 1:N) {
    kk[n] = categorical_rng(theta);
    mu[n] = x[n] * beta[kk[n]] + u[n] * gamma[kk[n]];
    y[n] = normal_rng(mu[n], sigma);
  }
}

Here is the generated data:

{
    "x": [
        -0.146162,
        1.00282,
        -1.06655,
        -0.608875
    ],
    "accept_stat__": 0,
    "D": 2,
    "mu": [
        -0.430974,
        -0.730549,
        -2.62693,
        -0.0629221
    ],
    "beta": [
        2.84695,
        0.722336,
        1.41036
    ],
    "sigma": 0.715999,
    "theta": [
        0.0145003,
        0.0734296,
        0.91207
    ],
    "lp__": 0,
    "kk": [
        3,
        3,
        3,
        3
    ],
    "gamma": [
        4.14439,
        2.3495,
        1.2581
    ],
    "N": 4,
    "u": [
        -0.178708,
        -1.70486,
        -0.892377,
        0.632552
    ],
    "K": 3,
    "y": [
        -1.39604,
        -1.38237,
        -2.38203,
        0.0383805
    ]
}

Then as part of my inference model I tried to use this (minimal example) but it fails with nan for x_beta.

data {
  int<lower=0> N;
  int<lower=1> K;
  real<lower=-10,upper=10> x[N];
  int<lower=1,upper=K> kk[N];
}
parameters {
  real mu_beta[K];
  real<lower=0> sigma_beta;
  real offset_beta[K];
}
transformed parameters {
  real<lower=-10,upper=10> x_beta[N];
  real<lower=10,upper=10> beta[K];
  for (n in 1:N) {
    real b = beta[kk[n]];
    print(b);
    x_beta[n] = x[n] * b;
  }
}
Rejecting initial value:
  Error evaluating the log probability at the initial value.
Exception: train_model_namespace::log_prob: x_beta[sym1__] is nan, but must be greater than or equal to -10.000000 (in '/tmp/jl_vSD7xy/train.stan', line 13, column 2 to column 37)

Initialization between (-2, 2) failed after 100 attempts. 
 Try specifying initial values, reducing ranges of constrained values, or reparameterizing the model.
Initialization failed.

This is because in your transformed parameters you’ve declared the vector beta but you haven’t assigned anything to it. This means that when you extract an element of beta and then assign it to x_beta, it’s assigning an unitialised value which then errors.

Should beta be a parameter or have something assigned to it first?