How to sort minimum value from a matrix
8 views (last 30 days)
Show older comments
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-
Accepted Answer
Bruno Luong
on 16 Jan 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
More Answers (2)
KSSV
on 16 Jan 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
on 16 Jan 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
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!