-
Notifications
You must be signed in to change notification settings - Fork 47
Compiling Stan components from Matlab
Brian Lau edited this page May 18, 2017
·
5 revisions
Before any model fitting can be done, Stan models must be translated to C++ code and compiled. This can be done automatically when using the stan
function. In addition, the StanModel
class exposes a method for compiling models, as well as the underlying Stan components. For example, to build the stan compiler:
model = StanModel('verbose',true);
model.compile('stanc');
The other main components of CmdStan can also be built (libstan.a
, libstanc.a
, stansummary
, and print
(deprecated)). Note that Matlab will be busy until compilation is finished.
We could then define a model and compile that too:
code = {
'data {'
' int<lower=0> N;'
' int<lower=0,upper=1> y[N];'
'}'
'parameters {'
' real<lower=0,upper=1> theta;'
'}'
'model {'
'for (n in 1:N)'
' y[n] ~ bernoulli(theta);'
'}'
};
model.set('model_code',code,'model_name','bernoulli');
model.compile();
Now we can fit a model, either by calling the sampling method directly
data = struct('N',10,'y',[0, 1, 0, 0, 0, 0, 0, 0, 0, 1]);
fit = model.sampling('data',data);
or by using the stan
function and passing in the defined model
fit2 = stan('fit',model,'data',data);