How to sort minimum value from a matrix
6 ビュー (過去 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!