function D = diagrep(D,k)
% Replicates model along the diagonal.
%
%   D = DIAGREP(D,K) forms the block-diagonal model Diag(D,...,D) with 
%   D repeated K times.

%   Copyright 1986-2010 The MathWorks, Inc.
[ny,nu,nz,nw] = getSignalSize(D);
yperm = localGetPerm(k,ny+nz,ny);
uperm = localGetPerm(k,nu+nw,nu);
if isnumeric(D.IC)
   IC = kron(eye(k),D.IC);  %#ok<*NASGU>
   D.IC = IC(yperm,uperm);
else
   IC = D.IC;  %#ok<*NASGU>
   for ct=2:k
      IC = append(IC,D.IC);
   end
   D.IC = ioperm(IC,yperm,uperm);
end
D.Blocks = repmat(D.Blocks,[k 1]);


function perm = localGetPerm(k,n,m)
perm = 1:k*n;
aux = (rem(perm-1,n)<m);
perm = [perm(aux) , perm(~aux)];