Closest Points between two datasets without using pdist2
古いコメントを表示
Hi, i have two matrices A, of size mx2, and B, of size nx2.
Each row of both matrices identifies a point in 2D space. What i want to do is to write a code, that does not involve loops and pdist2, as fast as possible, that tells me the indices of the row of both A and B such that the distance squared of the two points is the minimum one.
Example:
A=[5 6;
1 2;
3 4
1 8];
B=[3 0;
2 1;
4 1;
3 5;
1 2];
My function must be like [indA,indB]=function(A_matrix,B_matrix)
I want as output [2,5]=function(A,B)
I found a solution using for-loops but i really would like to find a solution using repmat that involves vectorization.
Thanks
4 件のコメント
Star Strider
2020 年 10 月 24 日
This appears to be a homework assignment.
Our policy here on MATLAB Answers is to offer only hints for such, not complete, working code.
Alberto Belvedere
2020 年 10 月 25 日
Walter Roberson
2020 年 10 月 25 日
repmat is slower than implicit expansion in many cases.
There are vectorized ways to get indices of the minimum, but they are not necessarily faster than using find() (would have to be tested) and would have problems with ties.
Alberto Belvedere
2020 年 10 月 25 日
採用された回答
その他の回答 (1 件)
Mitchell Thurston
2020 年 10 月 24 日
編集済み: Mitchell Thurston
2020 年 10 月 24 日
Came up with a solution:
[m,~] = size(A);
[n,~] = size(B);
A_rep = repmat(A,n,1);
B_rep = B';
B_rep = repmat(B_rep(:)',m,1);
dist = hypot( A_rep(:,1)-B_rep(:,1:2:end), A_rep(:,2)-B_rep(:,2:2:end) );
ind = find(dist == min(dist));
indB = floor((ind-1)./m)+1
indA = mod(ind-(indB-1)*m,n)
3 件のコメント
Alberto Belvedere
2020 年 10 月 24 日
Mitchell Thurston
2020 年 10 月 24 日
Not as far as I know, this is the method I've always used for cases like this. What is nice about this though is if there's a tie for the closest it will return all of those indicies of the tie.
Alberto Belvedere
2020 年 10 月 25 日
カテゴリ
ヘルプ センター および File Exchange で Surrogate Optimization についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!