Index of matrix using colon
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Christopher Longhurst
el 21 de Jun. de 2022
Comentada: Christopher Longhurst
el 22 de Jun. de 2022
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
0 comentarios
Respuesta aceptada
Image Analyst
el 21 de Jun. de 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);
Más respuestas (1)
Karim
el 21 de Jun. de 2022
Editada: Karim
el 21 de Jun. de 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
0 comentarios
Ver también
Categorías
Más información sobre Matrices and Arrays en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!