function G2_new = unfoldg2(G2,n)

% This function is designed to "unfold" matrix g_2 generated in the third
% order approximation of a policy function in Dynare.
% Arguments:
% G2 => matrix g_2, normally stored at oo_.dr.g_2, after the computation of
% a third-order approximation;
% n => number of state variables + shocks in the model

% Step 1: partition G2 matrix in "n" matrices with number of columns equal
% to n, n-1, n-2, n-3... 1.
i = 1;
while i < n+1
    eval(['G2' num2str(i) '= G2(:,(- n + (n + 1.5)*i - (i^2)/2): (i*n - (0.5*(i^2) - (0.5*i))) );'])
    i = i+1;
end

G2_new = zeros(size(G2,1),n^2);

% Step 2: build G2_new matrix with the partitions of G2.

for i = 1:n
    G2_new(:,i*(n+1)-n:i*n) = eval(['G2' num2str(i)]);  % position the partitions in their respective places
    for k = 2:n
        for j = k:i
            G2_new(:,(j-(k-1))*n+(k-2)*n+(k-1)) = eval(['G2' num2str(k-1) '(:,j-(k-2));']);  % position the partitions elements (columns) to set the symmetric terms
        end
    end
end


