How to find 2 closest numbers in a stream of arrays of the same size?
6 views (last 30 days)
Show older comments
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 Comments
Image Analyst
on 24 Jun 2015
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.
Answers (1)
Walter Roberson
on 24 Jun 2015
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.
2 Comments
See Also
Categories
Find more on Data Type Conversion 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!