find the closest point and taking the difference of y coordinates
1 view (last 30 days)
Show older comments
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
1 Comment
Adam
on 7 Aug 2019
[~,idx] = min( distances );
B(idx,:);
should give you what you want, more simply, though it ought to just be a simpler version of what you have there. You didn't say what is wrong with it though other than 'didn't get the desired result'. What did you get?
Accepted Answer
Adam Danz
on 7 Aug 2019
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,:)
0 Comments
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!