# Sampling from a matrix in STAN

You can’t define functions within functions, you need to declare the rng function separately and then call it within your function

1 Like

I got the following error when running the model.

Found negative dimension size in variable declaration; variable=Gender; dimension size expression=n; expression value=-2147483648

This is the stan code defined in a user-defined `_rng` function.

``````vector[n] Gender;
for (i in 1:n){
Gender[i] = binomial_rng(1,0.5);
}
``````

Can someone explain me why this error happens

Thank you

Presumably because n is negative?

Hi @jsocolar ,

I don’t still know how to solve it because I put `n=100`

Thanks

Can you post your full stan code? This error indicates that `n` has not been given a value before it’s been used

Hi @andrjohns,

That means do I need to give an initial value for `n`? Also, I have a new error

`algebra_solver: parameter vector is nan, but must be finite`

Okay, please see attached stan code and help me to make it run.
model2.stan (8.9 KB)

Thank you

The error for `n` is caused by this section:

``````matrix data_rng(real m, real mu_diag, real mu_reg, real mu_dist){
int n ;
...
vector[n] Gender;
``````

You declared the int variable `n` and are using it for indexing, but you haven’t given it a value, so Stan doesn’t know what size these vectors should be or what length to loop over

Thank you Andrew.
Okay, I set it `n = 100` within my user-defined function `data_rng` (is it correct?) and run the model.
Then it gave me this error `algebra_solver: parameter vector is nan, but must be finite`

This is the first time I am using an algebraic solver in stan and I don’t much about it. So, can you please explain to me how to solve it?

Thank you

That error indicates that at least one of the values being passed to the `algebra_solver` function is `nan`, try using the `print` function to print the values of the parameters that you’re using as inputs, to see which parameters are `nan`

1 Like