MATLAB: Find the closest point and taking the difference of y coordinates

MATLAB

let assume I have A matrix in which there are m points and B matrix in which n points are there
I have a point lets say m1(x,y) in A matrix ,I want to find its closest/correspondent point in B matrix and after that want to differentiate the y coordinates of m1 point and its closest point
then taking m2(x,y) of A matrix finding it closest point in B matrix and diffrentiate and so on for each point in A matrix i want closest point in B matrix and diffrentiate their repsective y coordinates
I have tries some function/code like
1)"k = dsearchn(X,XI)"
2)
A = rand(1,2);
B = rand(10,2);
%compute Euclidean distances:
distances = sqrt(sum(bsxfun(@minus, B, A).^2,2));
%find the smallest distance and use that as an index into B:
closest = B(find(distances==min(distances)),:);
but didnt get the desired result
I am using matlab2014a

Best Answer

I recommen using pdist2() to calculate a matrix of distances between all points in A and all points in B. See comments within the block of code below.
% produces fake data
A = randi(100,3,2);
B = randi(100,5,2);
distance = pdist2(A,B);
% distance(i,j) is the distance between A(i,:) and B(j,:)
To find the nearest point in B to A(m,:),
% for m = 2, the row in B closest to A(m,:) is "minIdx"
m = 2;
[~, minIdx] = min(distance(m,:));
I didn't follow the second part of your quesiton but here's how to pull those two coordinates from A and B.
m2 = A(m,:)
n2 = B(minIdx,:)