function [K2] = kneighbor(K1, D, varargin)
% Neighborhood kernel. 
%
% Input:
%   K -- kernel matrix
%   D -- distance matrix
%   varargin -- type + parameter:
%       'k', k
%       'eps', eps
% Output: 
%   K2 -- kernel matrix
%
% (c) 2008-2016 Zalan Bodo

N = size(K1, 1);
K2 = zeros(N, N);

p{1} = 'k';
p{2} = 3;
for i = 1:size(varargin, 2)
    p{i} = varargin{i};
end
k = p{2};

if p{1} == 'k'
    [tmp, ind] = sort(D);
    for i = 1:N
        for j = 1:N
%            K2(i,j) = mean(K1(sub2ind([N, N], ind(1:k+1,i), ind(1:k+1,j))));
            K3 = K1(ind(1:k+1,i), ind(1:k+1,j));
            K2(i,j) = sum(sum(K3))/(size(K3, 1)*size(K3, 2));
        end
    end
elseif p{1} == 'eps'
    for i = 1:N
        for j = 1:N
            a = find(D(i,:) <= k);
            b = find(D(j,:) <= k);
            K2(i,j) = sum(sum(K1(a,b)))/(size(a, 1)*size(b, 1));
        end
    end    
end
