function j = findNN2d(i, ARRAY);

% findnn2d(i, <ARRAY>) -- Find the 2D nearest neighbor to point i in an array.
%
% The findnn() function takes the array <ARRAY>, and selects 
% individual number <i> in the array (the i-th row) and finds (out of
% the rest of the array) the nearest neighbor of individual i. That neighbor
% is individual number j, and is then returned by the function.
% 
% This function doesn't do "square root" while finding the nearest neighbor 
% (since, if X < Y then X^2 < Y^2). 
%
% Example:
% PTS = [1, 1, 0,0,0; 1, 2, 9,9,9; 1, 3,1,1,1; 1, 4,8,8,8; 1, 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 = findnn3d(3,PTS);
% J =
%	   1
% Thus, point # 1 is the closest individual to point #3


% Currently this is an N^2 algorithm. We search every point and find
% the distance from i to every point. Then we find out which one matches
% the minimum.



N = size(ARRAY,1);

% Initialize the minimum distance at infinitiy;
min_dist = Inf;

n = i;						
for m = 1:N						% for each other point in the group
	if (m ~= n)
		x1 = ARRAY(n,3);
		y1 = ARRAY(n,4);
		x2 = ARRAY(m,3);
		y2 = ARRAY(m,4);
		dist = (x2-x1)^2 + (y2 - y1)^2;
		if ( dist < min_dist );
			% The distance is smaller than the previously recorded minimum,
			% so THAT is the minimum, and this individual's number is
			% the one that is the nearest (so far) neighbor.
			min_dist = dist;
			nearest_neighbor = m;
		end
		
	end		
end

j = nearest_neighbor;

