How to find 2 closest numbers in a stream of arrays of the same size?
5 次查看(过去 30 天)
显示 更早的评论
Hi, I want to get the index and the numbers that is closest to 2 points that i select. For example, my input is
My input is:
12.6600 83.5567
10.9106 87.1264
8.5950 91.9967
For each point, i want to find the closest matching point in a larger array and its corresponding index. My larger array is :
12.0990 83.3643
12.0963 83.3725
12.0935 83.3801
12.0905 83.3883
10.7051 87.1957
10.7024 87.2033
10.6993 87.2115
8.5992 91.9872
8.5954 91.9954
8.5920 92.0029
8.5882 92.0105
8.5844 92.0187
8.5807 92.0263
8.5772 92.0338
8.5735 92.0421
The input numbers can also be negative. Can you please suggest if there is any inbuilt function which can do the search?
3 个评论
Image Analyst
2015-6-24
I see the two input arrays, the small 3-row one, and the larger 15-row one. But I don't know which of those 18 points are the "2 points that i select" . Which two are you selecting? And which of the remaining 16 points in the two arrays do you want to check the distance to? For one example, both points are in the small array and you want to compare those to only points in the big array? Or maybe, you select one point in the small array and one point in the big array, and you want to find distances from each of those two points to all the other points in both arrays? Or what??? Please explain.
回答(1 个)
Walter Roberson
2015-6-24
xdiff = bsxfun(@minus, smallarray(:,1), largearray(:,1).');
ydiff = bsxfun(@minus, smallarray(:,2), largearray(:,2).');
distmat = sqrt(xdiff.^2 + ydiff.^2);
[closestdist, closestidx] = min(distmat,2);
and now closestidx is a vector the same length as the number of rows in smallarray, with the each element giving the index of the row in largearray that is closest (euclidean distance) to the row in the smallarray.
Note that this is a Euclidean distance calculation, and does not take into account crossing +/- 180, and does not take into account the variation in longnitude as latitude increases. If those are important than a different formula would be needed: http://www.mathworks.com/help/map/ref/distance.html
[LAT1, LAT2] = ndgrid(smallarray(:,1), largearray(:,1));
[LONG1, LONG2] = ndgrid(smallarray(:,2), largearray(:,2));
LL1 = [LAT1(:), LONG1(:)];
LL2 = [LAT2(:), LONG2(:)];
distmat = zeros(size(LAT1));
for K = 1 : size(LL1,1)
distmat(K) = distance(LL1(K,:), LL2(K,:));
end
[closestdist, closestidx] = min(distmat,2);
Untested code; I do not have the mapping toolbox.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!