How to sort minimum value from a matrix
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Shin
el 16 de En. de 2023
Comentada: Shin
el 16 de En. de 2023
Hi there, I have 2 set of array such as
number = 6;
A = 1+10*(rand(number,2));
B = [4,8; 6,8; 8,8; 6,6.7; 6,5.4; 6,4.1];
% Calculate all distance between set A and B for each elements
s = size(A);
dist = cell(1,s(1));
for idx = 1:s(1)
dist{idx} = vecnorm(B - A(idx,:),2,2);
end
dist = cell2mat(dist);
[minDist,index] = min(dist(:,:)); % obtain min distance and their index
The first set A is generated randomly and the second set B is fixed, and after running the code it will give a list of results such as
each column represent the distance from each element from set A to all in the set B. And the index indicate in which row the minium value located at. Hence, I was wondering how can sort the minimun value out, given that there might be huge posiballity of one of the point have the same minimun distance point as the figure show for index. If than happen, I would like to find the second minimum value to be the minimin value to ensure it wont obtain the same index of minimun value. For example, the index I would like to have the number 1 to 6 for each column and not repeated. Thanks.
-Chann-
Respuesta aceptada
Bruno Luong
el 16 de En. de 2023
number = 6;
A = 1+10*(rand(number,2));
B = [4,8; 6,8; 8,8; 6,6.7; 6,5.4; 6,4.1];
% Calculate all distance between set A and B for each elements
s = size(A);
dist = cell(1,s(1));
for idx = 1:s(1)
dist{idx} = vecnorm(B - A(idx,:),2,2);
end
dist = cell2mat(dist)
M = matchpairs(dist,max(dist,[],'all'));
for k=1:size(M,1)
fprintf('Column %d matches row %d, dist(i,j) = %f\n', M(k,2), M(k,1), dist(M(k,1),M(k,2)))
end
Más respuestas (2)
KSSV
el 16 de En. de 2023
number = 6;
A = 1+10*(rand(number,2));
B = [4,8; 6,8; 8,8; 6,6.7; 6,5.4; 6,4.1];
idx = knnsearch(A,B)
Image Analyst
el 16 de En. de 2023
Try this:
number = 6;
A = 1+10*(rand(number,2))
B = [4,8; 6,8; 8,8; 6,6.7; 6,5.4; 6,4.1]
distances = pdist2(A, B)
% Find unique distances because it's possible some may be repeated.
udistances = unique(distances) % It's also sorted from in to max
% Find row and column for all the distances, from shortest to longest in sorted order.
for k = 1 : numel(udistances)
thisDistance = udistances(k);
fprintf('Min distance of %f at\n', thisDistance);
[indexA, indexB] = find(distances == thisDistance) % It's possible there will be multiple indexes if using integer coordinates.
end
Ver también
Categorías
Más información sobre Matrix Indexing 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!