function[fval, IRF_model]=IRF_matching_objective(xopt,IRF_target,weighting_matrix) %#ok<INUSD>
        global oo_ M_ options_  %#ok<NUSED> %required input structures for call to stoch_simul
IRF_model=[oo_.irfs.y_eetai' oo_.irfs.pie_eetai' oo_.irfs.rm_eetai' oo_.irfs.rl_eetai' oo_.irfs.c_eetai' oo_.irfs.invest_eetai'];
% set parameters for use in Dynare

set_param_value ('tau',xopt(1));
set_param_value ('ind_p',xopt(2));
set_param_value ('ind_w',xopt(3));
set_param_value ('thetap',xopt(4));
set_param_value ('v',xopt(5));
set_param_value ('thetaw',xopt(6));
set_param_value ('eta',xopt(7));
set_param_value ('h',xopt(8));

 
 if any(xopt<=0.15) || any(xopt(1)>=0.9) || any(xopt(2)>=1) || any(xopt(3)>=1) || any(xopt(4)>=1) || any(xopt(5)>=1) || any(xopt(6)>=1) || any(xopt(7)>=2.5) || any(xopt(8)>=0.89)   
    
    %#ok<ALIGN>
    %make sure roots are between 0 and 1
    fval=10e6+sum((xopt).^2);  % penalty function
    
    return    
end


info=stoch_simul([]);


if info % solution was not successful
    fval=10e6+sum((xopt).^2); % return with penalty
else   
IRF_model=[oo_.irfs.y_eetai' oo_.irfs.pie_eetai' oo_.irfs.rm_eetai' oo_.irfs.rl_eetai' oo_.irfs.c_eetai' oo_.irfs.invest_eetai']; % select desired IRFs
%compute objective function (omitting the impact response etar)
fval=(IRF_model(2:end)-IRF_target(2:end))*weighting_matrix*(IRF_model(2:end)-IRF_target(2:end))';
end