I’m trying to numerically calibrate my model by setting to zero (or minimizing) the distance between data moments and model moments. My Matlab code is something similar to:

```
dynare('model.mod')
param_0 = 0.1;
x0(1) = param_0;
target_moments(1) = 1;
options = optimset(...);
[calibrated_params FFinal] = fsolve(@(x) moment_distance(x, target_moments, M, oo, var_list), param_0, options);
function V = moment_distance(x,target_moments, M, oo, var_list)
param = x(1);
[info, oo_, options_] = stoch_simul(M, options, oo, var_list);
% Say model target moment is located at oo_.var(1,1)
V(1) = target_moments(1) - oo_.var(1,1);
end
```

The problem with this is that checking the values `V`

takes, I note that they never change when the solver tries different values, resulting in not finding a solution as the function is regular. This is wrong since I’ve already done parameter identification and moments do change when I change parameter values.

I think this comes from the fact that running `stoch_simul()`

locally in a function without having run `dynare('model.mod')`

alone first is not the same as running this first, since it sets-up the environment with `M_`

, `oo_`

, `options_`

, `var_list_`

variables.

Nonetheless, if I change my function to:

```
function V = moment_distance(x,target_moments)
dynare('model.mod')
param = x(1);
[info, oo_, options_] = stoch_simul(M_, options_, oo_, var_list_);
% Say model target moment is located at oo_.var(1,1)
V(1) = target_moments(1) - oo_.var(1,1);
end
```

I now obtain an error inside the function which prompts that `M_`

( and I guess the other related variables) does not exist. I’m not sure what should I do in order to get Dynare changing effectively the parameter values for iteration and trying to find a solution, I’d be very grateful with some help.

Thanks!