function Y = mybackoutshocks(THIS,Y,IALT)

try
    IALT; %#ok<VUNUS>
catch %#ok<CTCH>
    IALT = 1;
end

%**************************************************************************

maxlag = -THIS.mint;
maxlead = THIS.maxt;
nxper = size(Y,2);
t = 1+maxlag : nxper-maxlead;
nonidentindex = isnan(THIS.ident);

% `Y` is nname-by-nper; permute `Y` to 1-by-nname-by-nper.
Y = permute(Y,[3,1,2]);

% Create vector of steady-state values.
L = real(THIS.Assign(1,:,IALT));

oo = optimset('display','none');
throwwarning = false;
for it = t
    e0 = Y(1,THIS.nametype == 3,it);
    e0(~isfinite(e0)) = 0;
    e1 = lsqnonlin(@doresiduals,e0,[],[],oo);
    Y(1,THIS.nametype == 3,it) = e1;
end

if throwwarning
    utils.warning('syeq', ...
        ['Cannot back out shocks because ', ...
        'some equations evaluate to NaN in some periods.']);
end

Y = ipermute(Y,[3,1,2]);

% Nested functions.

%**************************************************************************
    function u = doresiduals(x)
        % Assign current shocks.
        Y(1,THIS.nametype == 3,it) = x;
        % Compute residuals from non-ident equations.
        u = nan(0,1);
        for ieq = find(nonidentindex)
            u(end+1,:) = THIS.eqtnf{ieq}(Y,it,L); %#ok<AGROW>
        end
        % Vectorize the residuals.
        u = u(:).';
        index = ~isfinite(u);
        if any(index)
            u(index) = 0;
            throwwarning = true;
        end
    end
% doresiduals().

end