MATLAB: Find nearest neighbors between points of 2 matrix (x,y)

distanceknnsearchMATLABmatrixnearest neighborspythagorean

I have 2 matrices, containing x,y data
A is a matrix with two columns, A= [X,Y], that give the position x and y. With 56 in length
B is a matrix with two columns, B= [X,Y], that give the position x and y. With 107 in length
I would like to know,for all points of matrix B, which is the nearest A point, and save the id of this point with its informations(x,y data).
i found the knnsearch command that maybe can do this, but i have not idea how to use it

Best Answer

The simplest and best solution IMHO is to stick with the basics: the Pythagorean distance formula in a loop.
% Create some fake data
A = rand(56,2).*10;
B = rand(107,2).*10;
% for each (x,y) pair in B, find the row in A that is nearest.
nearestIdx = zeros(size(B,1),1);
for i = 1:size(B,1)
d = sqrt((B(i,1)-A(:,1)).^2 + (B(i,2)-A(:,2)).^2); %distance between B(i) and all A
[~, nearestIdx(i)] = min(d); %Index of A that is nearest to B(i)
end
% List the (x,y) coordinates in A that are closest to B in same order as B.
A(nearestIdx,:) % the (x,y) coordinates of A nearest to B
If you'd like to take that a step further and visualize the connections made between B and A,
figure
plot(A(:,1),A(:,2), 'ro','markersize',5,'MarkerFaceColor','r')
hold on
plot(B(:,1),B(:,2), 'bo','markersize',5,'MarkerFaceColor','b')
plot([A(nearestIdx,1)';B(:,1)'], [A(nearestIdx,2)';B(:,2)'], 'k-')
legend({'A', 'B', 'Connection'}, 'Location', 'BestOutside')
axis equal