Index of matrix using colon
Show older comments
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
More Answers (1)
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
Categories
Find more on Logical 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!