function ALL = allnn2d(ARRAY);

% allnn2d(<array>) -- Find nearest neighbors for all points in an array.
%
% The allnn2d() function takes the array <array>, and finds all the individuals
% in the array's nearest neighbors, which are identified in the first column of
% of the output matrix,as well as the distance to that neighbor, which is placed
% in the second column.
%
% Example:
% >> PTS = [1,0,0; 2,9,9; 3,1,1; 4,8,8; 5,11,11]
% PTS =
% 
%      1     0     0     
%      2     9     9     
%      3     1     1     
%      4     8     8     
%      5    11    11    
% >> J = allnn2d(PTS)
% 
% J =
% 
%      3     1.0          
%      4     1.0
%      1     1.0
%      2     1.0
%      2     2.8

% At the moment, this is an N^2 algorithm.

DIST = [];  						% initialize the DISTance matrix
NN = [];							% initialize the Nearest Neighbor matrix
N = size(ARRAY,1);

for n = 1:N							% loop over every point and find distance
	for m = 1:N						%  for each other point in the group
		if (m == n)
			DIST(n,m) = 999;
		else
			x1 = ARRAY(n,2);        % Takes the point under consideration out
			y1 = ARRAY(n,3);        %  of the array (row n).

			x2 = ARRAY(m,2);        % Checks each other point, (row m0).
			y2 = ARRAY(m,3);          

			DIST(n,m) = dist2d(x1,y1,x2,y2);    % Checks the distances.
		end		
	end
    
    % Now, finds smallest distance in the DIST matrix, which is the NND for 
    % that point (row n). 
	%NN = [NN; match(DIST(n,:),min(DIST(n,:))) min(DIST(n,:))];
	NN = [NN; n min(DIST(n,:))];
end

ALL = NN;
