function K = subkron (A,B,IND)

%
% Kronecker product of A and B at rows and columns specified in IND
% It is much faster than indexing after ordinary kron
%

ma = size(A,1);
mb = size(B,1);

J = mod(IND-1,mb)+1;
I = (IND-J)/mb+1;

MA = cell (ma,1);
MB = cell (mb,1);
SMA = zeros (ma,1);
SMB = zeros (mb,1);

for i = 1:size(I,1)
    k = I(i);
    SMA(k) = SMA(k) + 1;
    MA{k}(SMA(k)) = i;
    k = J(i);
    SMB(k) = SMB(k) + 1;
    MB{k}(SMB(k)) = i;
end

[IA,JA,SA] = find (A);
L = transpose(SMA(IA))*SMA(JA);
IK = zeros(L,1);
JK = zeros(L,1);
SK = zeros(L,1);
j = 1;
for i = 1:size(SA,1)
    IC = MA{IA(i)}';
    JC = MA{JA(i)}';
    sic = size(IC,1);
    sjc = size(JC,1);
    if (sic == 0 || sjc == 0)
        continue;
    end
    IO = ones(sic,1);
    JO = ones(sjc,1);
    JC = JC';
    IK0 = IC(:,JO);
    JK0 = JC(IO,:);
    SK0 = SA(i)*ones(sic,sjc);
    INT = j:(j+SMA(IA(i))*SMA(JA(i))-1);
    IK(INT) = IK0(:);
    JK(INT) = JK0(:);
    SK(INT) = SK0(:);
    j = j+SMA(IA(i))*SMA(JA(i));
end

AX = sparse (IK,JK,SK,size(I,1),size(I,1));

[IA,JA,SA] = find (B);
L = transpose(SMB(IA))*SMB(JA);
IK = zeros(L,1);
JK = zeros(L,1);
SK = zeros(L,1);
j = 1;
for i = 1:size(SA,1)
    IC = MB{IA(i)}';
    JC = MB{JA(i)}';
    sic = size(IC,1);
    sjc = size(JC,1);
    if (sic == 0 || sjc == 0)
        continue;
    end
    IO = ones(sic,1);
    JO = ones(sjc,1);
    JC = JC';
    IK0 = IC(:,JO);
    JK0 = JC(IO,:);
    SK0 = SA(i)*ones(sic,sjc);
    INT = j:(j+SMB(IA(i))*SMB(JA(i))-1);
    IK(INT) = IK0(:);
    JK(INT) = JK0(:);
    SK(INT) = SK0(:);
    j = j+SMB(IA(i))*SMB(JA(i));
end

BX = sparse (IK,JK,SK,size(I,1),size(I,1));

K = AX.*BX;
