Index of matrix using colon

1 view (last 30 days)
I have a matrix of points split into two by X and Y (both 2D arrays) and another matrix of specific points split into two by X and Y (again both 2D arrays). I wish to find the closest point in the main matrix to each point in my other matrix.
for i = 1:length(Xpoints)
[~,Index] = min(sqrt(abs(mainmatrixX(:)-Xpoints(i) + sqrt(abs(mainmatrixY(:)-Ypoints(i))))));
end
this only ever returns the index value of 1 i assume because it's not taking the position of the colon.
Any help would be much appreciated

Accepted Answer

Image Analyst
Image Analyst on 21 Jun 2022
If you have the Statistics and Machine Learning Toolbox you can use pdist2 to get the distance from every point in set 1 to every point in set 2, then use min and find to find the indexes of the closest. Untested code (because you forgot to attach your data):
% Get all distances
xy1 = [x1(:), y1(:)];
xy2 = [x2(:), y2(:)];
distances = pdist2(xy1, xy2);
% Find closest (minimum) distance.
minDistance = min(distances)
% Find out where it occurs
[rowInSet1, rowInSet2] = find(distances == minDistance)
x1Closest = xy1(rowInSet1, 1);
y1Closest = xy1(rowInSet1, 2);
x2Closest = xy2(rowInSet2, 1);
y2Closest = xy2(rowInSet2, 2);

More Answers (1)

Karim
Karim on 21 Jun 2022
Edited: Karim on 21 Jun 2022
you need to save the index value into a new array, otherwise it will overwrite the value and only keep the last one
mainmatrixX = rand(100,1);
mainmatrixY = rand(100,1);
Xpoints = rand(100,1);
Ypoints = rand(100,1);
ImClosest = zeros(length(Xpoints),1);
for i = 1:length(Xpoints)
[~,currIndex] = min(sqrt( (mainmatrixX(:)-Xpoints(i)).^2 + (mainmatrixY(:)-Ypoints(i)).^2 ));
ImClosest(i) = currIndex;
end
ImClosest
ImClosest = 100×1
51 79 69 38 19 44 95 33 49 50

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Tags

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!