function SpMAT = SparsMaker(X, Y, Z, dim) %(X,Y,Z, dim)% This code creates the sparse matrix used in heterogeneous agent models in continuous% time. This can be applied to any number of states or dimensions.
% BY SAEED SHAKER-AKHTEKHANE
% X, Y and Z (or chi, yy, zeta) can be N-Dim. The dimension of X, Y and Z must agree with the number of% state variables. Argument dim takes values from 1 to N, and corresponds to the dimension of interest. For% instance we may have wealth (a) specified in 1st dimention, capital (k) in the% 2nd dimension and shock (z) in the 3rd dimension, and so on...
dimsAll = size(Z); % All dimensionsdimMult = numel(Z); % All dimensions multiplieddimMultLess = prod(dimsAll(1:dim-1)); % All dimensions before dim multiplieddimeln = dimsAll(dim); % number of elements in the dimension of interest%S.type = '()';X_st = reshape(X,[dimMult,1]);Y_st = reshape(Y,[dimMult,1]);Z_st = reshape(Z,[dimMult,1]);
lowdiag=[];centdiag = zeros(dimMult,1);updiag=zeros(dimMultLess,1);
indicat_1 = zeros(dimMult,1); % this indicator finds the elements for which the dimension of interest is 1indicat_end = zeros(dimMult,1); % this indicator finds the elements for which the dimension of interest is end for i01 = 1:dimMultLess*dimeln:dimMult-1 indicat_1(i01:i01+dimMultLess-1) = 1; end for i01 = dimMultLess*(dimeln-1)+1:dimMultLess*dimeln:dimMult-1 indicat_end(i01:i01+dimMultLess-1) = 1; end Y_st = Y_st + indicat_1.*X_st; X_st = X_st.*(1 - indicat_1); Y_st = Y_st + indicat_end.*Z_st; Z_st = Z_st.*(1 - indicat_end); lowdiag=[lowdiag;X_st];centdiag = Y_st;updiag=[updiag;Z_st];
lowdiag(1:dimMultLess) = [];
SpMAT = spdiags(centdiag,0,dimMult,dimMult)... + spdiags(updiag,dimMultLess,dimMult,dimMult)... + spdiags(lowdiag,-dimMultLess,dimMult,dimMult);