function K = kron(A,B)
%KRON   Kronecker tensor product.
%   KRON(X,Y) is the Kronecker tensor product of X and Y.
%   The result is a large matrix formed by taking all possible
%   products between the elements of X and those of Y.   For
%   example, if X is 2 by 3, then KRON(X,Y) is
%
%      [ X(1,1)*Y  X(1,2)*Y  X(1,3)*Y
%        X(2,1)*Y  X(2,2)*Y  X(2,3)*Y ]
%
%   If either X or Y is sparse, only nonzero elements are multiplied
%   in the computation, and the result is sparse.

%   Paul L. Fackler, North Carolina State, 9-23-96
%   Copyright (c) 1984-98 by The MathWorks, Inc.
%   $Revision: 5.10 $ $Date: 1997/11/21 23:39:55 $


[ma,na] = size(A);
[mb,nb] = size(B);

if issparse(A) | issparse(B)

   % At least one input is sparse, result is sparse.

   [ia,ja,sa] = find(A);
   [ib,jb,sb] = find(B);
   ia = ia(:); ja = ja(:); sa = sa(:);
   ib = ib(:); jb = jb(:); sb = sb(:);
   ka = ones(size(sa));
   kb = ones(size(sb));
   t = mb*(ia-1)';
   ik = t(kb,:)+ib(:,ka);
   t = nb*(ja-1)';
   jk = t(kb,:)+jb(:,ka);
   K = sparse(ik,jk,sb*sa.',ma*mb,na*nb);

else

   % Both inputs full, result is full.

   t = 0:(ma*mb-1);
   ia = fix(t/mb)+1;
   ib = rem(t,mb)+1;
   t = 0:(na*nb-1);
   ja = fix(t/nb)+1;
   jb = rem(t,nb)+1;
   K = A(ia,ja).*B(ib,jb);

end
