function[fval, IRF_model]=IRF_matching_objective(xopt,IRF_target,weighting_matrix) %#ok<INUSD>
    IRF_model=[];

global oo_ M_ options_ %#ok<NUSED> %required input structures for call to stoch_simul


% 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 ('v',xopt(4));
set_param_value ('thetap',xopt(5));
set_param_value ('thetaw',xopt(6));

if  any(xopt<=0.65)  ||  any(xopt(1)>=1) %make sure roots are between 0 and 1
    any(xopt<=0.4)   ||  any(xopt(1)>=1)
    any(xopt<=0.36)  ||  any(xopt(1)>=1) %#ok<NOPRT>
    any(xopt<=0.5)   ||  any(xopt(1)>=1)
    any(xopt<=0.75)  ||  any(xopt(1)>=1)
    any(xopt<=0.5)   ||  any(xopt(1)>=1)
    
    fval=10e6+sum([xopt].^2);%#ok<NBRAK> % penalty function
    
    return    
end

info=stoch_simul([]);%run stoch_simul to generate IRFs with the options specified in the mod-file

if info % solution was not successful
    fval=10e6+sum([xopt].^2); %#ok<NBRAK> % return with penalty
else   
IRF_model=[oo_.irfs.y_eetar ' oo_.irfs.pie_eetar' oo_.irfs.rm_eetar ' oo_.irfs.rl_eetar']; % 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