function ALL = allnn3d(ARRAY);

% allnn3d(<array>) -- Find nearest neighbors for all points in an array.
%
% The allnn3d() function takes the array <array>, and finds all the individuals
% in the array's nearest neighbors.
%
% Example:
% >> PTS = [1, 0,0,0; 2, 9,9,9; 3,1,1,1; 4,8,8,8; 5,11,11,11]
% PTS =
% 
%      1     0     0     0
%      2     9     9     9
%      3     1     1     1
%      4     8     8     8
%      5    11    11    11
% >> J = allnn3d(PTS)
% 
% J =
% 
%      3
%      4
%      1
%      2
%      2

% 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);
			y1 = ARRAY(n,3);
			z1 = ARRAY(n,4);
			x2 = ARRAY(m,2);
			y2 = ARRAY(m,3);
			z2 = ARRAY(m,4);
			DIST(n,m) = dist3d(x1,y1,z1,x2,y2,z2);
		end		
	end
	NN = [NN; match(DIST(n,:),min(DIST(n,:)))];
end


ALL = NN;
