function results = neighbors_cum(L,k)

%NEIGHBORS_CUM computes the values of the first k nearest neighbors to points.

%WRITTEN BY: Tony E. Smith, 2/22/01

%INPUTS: L = (Nx2) matrix of (Xi,Yi) = coordinates
%        
%   		k = order of the nearest neighbors to be considered.

%        
%NOTE: The program produces only one kth neighbor (the first one found)
%      and hence is not appropriate for regular grid data.
%
%OUTPUTS: results = output structure with:
% 
%           results.list = (Nxk)-matrix, M, with 
%                           M(i,j) = row numbers of first j 
%                                    nearest neighbors to i
%                          
%             result.wts = (NxN) normalized weight matrix, W, with 
%                           W(i,j) = 1/k iff j is one of the first
%                                    k nearest neighbors of i.


N = size(L,1) ;

M = zeros(N,k); %List Matrix

W = zeros(N,N); %Weight Matrix

if max(k,N)==k 
   
   error('k is too big for data set'); 
   
end


p = k + 3 ;

for i = 1:N
   
   D = sqrt( (L(i,1)-L(:,1)).^2 + (L(i,2) - L(:,2)).^2 ); %distances to i
   
   D(i)= max(D) + 1 ; %Eliminate diagonal elements as n-neighbors.   
    
   Y(:,1) = [1:N]' ;
   
   Y(:,2) = D ;
   
   Y = sortrows(Y,2) ; %orders distances to i
   
   M(i,:) = Y(1:k,1)';   
   
   W(i,M(i,:)) = 1;
   
   W = row_norm(W);        
     
end

results.list = M;

results.wts = W;

   
  
