How to sort minimum value from a matrix
조회 수: 5 (최근 30일)
이전 댓글 표시
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-
채택된 답변
Bruno Luong
2023년 1월 16일
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
추가 답변 (2개)
KSSV
2023년 1월 16일
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
2023년 1월 16일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!