1function y = irf(M_, options_, dr, e1, long, drop, replic, iorder)
2% function y = irf(M_, options_, dr, e1, long, drop, replic, iorder)
3% Computes impulse response functions
4%
5% INPUTS
6%    M_:        structure representing the model
7%    options_:  structure representing options for commands
8%    dr:        structure of decisions rules for stochastic simulations
9%    e1:        exogenous variables value in time 1 after one shock
10%    long:      number of periods of simulation
11%    drop:      truncation (in order 2)
12%    replic:    number of replications (in order 2)
13%    iorder:    first or second order approximation
14%
15% OUTPUTS
16%    y:      impulse response matrix
17%
18% SPECIAL REQUIREMENTS
19%    none
20
21% Copyright (C) 2003-2019 Dynare Team
22%
23% This file is part of Dynare.
24%
25% Dynare is free software: you can redistribute it and/or modify
26% it under the terms of the GNU General Public License as published by
27% the Free Software Foundation, either version 3 of the License, or
28% (at your option) any later version.
29%
30% Dynare is distributed in the hope that it will be useful,
31% but WITHOUT ANY WARRANTY; without even the implied warranty of
32% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
33% GNU General Public License for more details.
34%
35% You should have received a copy of the GNU General Public License
36% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
37
38if M_.maximum_lag >= 1
39    temps = repmat(dr.ys,1,M_.maximum_lag);
40else
41    temps = zeros(M_.endo_nbr, 1); % Dummy values for purely forward models
42end
43y       = 0;
44
45local_order = iorder;
46if local_order~=1 && M_.hessian_eq_zero
47    local_order = 1;
48end
49
50if local_order == 1
51    y1 = repmat(dr.ys,1,long);
52    ex2 = zeros(long,M_.exo_nbr);
53    ex2(1,:) = e1';
54    y2 = simult_(M_,options_,temps,dr,ex2,local_order);
55    y = y2(:,M_.maximum_lag+1:end)-y1;
56else
57    % eliminate shocks with 0 variance
58    i_exo_var = setdiff([1:M_.exo_nbr],find(diag(M_.Sigma_e) == 0 ));
59    nxs = length(i_exo_var);
60    ex1 = zeros(long+drop,M_.exo_nbr);
61    chol_S = chol(M_.Sigma_e(i_exo_var,i_exo_var));
62    for j = 1: replic
63        ex1(:,i_exo_var) = randn(long+drop,nxs)*chol_S;
64        ex2 = ex1;
65        ex2(drop+1,:) = ex2(drop+1,:)+e1';
66        y1 = simult_(M_,options_,temps,dr,ex1,local_order);
67        y2 = simult_(M_,options_,temps,dr,ex2,local_order);
68        y = y+(y2(:,M_.maximum_lag+drop+1:end)-y1(:,M_.maximum_lag+drop+1:end));
69    end
70    y=y/replic;
71end
72