How to find index of closest value in a column array for every value in another column array.

2 次查看(过去 30 天)
I have an array called 'loc' that contains longitudes in the first column and latitudes in the second column. Additionally, I have an array called 'lonlat' that contains longitudes in the first column and latitudes in the second column. For every latitude and longitude pair in 'lonlat' I need to find the index of the closest latitude and longitude pair in 'loc'. 'lonlat' and 'loc' both have two columns but they have a different number of rows.

回答(1 个)

Jorge Mario Guerra González
编辑:Jorge Mario Guerra González 2017-1-21
You can adapt this according to your needs.
you just have to use loops to make a serires of comparations. Also you have to know how to messure the the distance using longitude and latitude.
Check if this works.
loc=360*rand(20,2)-180;
lonlat=360*rand(5,2)-180;
closest=zeros(size(lonlat,1),3);
aux=zeros(size(loc,1),1);
R=6373; %Km
for i=1:size(lonlat,1)
lon2=lonlat(i,1); lat2=lonlat(i,2);
for j=1:size(loc,1)
lon1=loc(j,1); lat1=loc(j,2);
dlon = lon2 - lon1;
dlat = lat2 - lat1 ;
a = (sin(dlat/2))^2 + cos(lat1) * cos(lat2) * (sin(dlon/2))^2;
c = 2 * atan2( sqrt(a), sqrt(1-a) ) ;
d = R * c; %where R is the radius of the Earth
aux(j)=d;
end
idx=find(aux==min(aux(:)));
closest(i,1:2)=loc(idx,:);
closest(i,3)=aux(idx);
end
I made use some random lons and lats, the algorithm to calculate the distance was taken from this site.
closest is the result matrix, which has the closest coordinate from loc for each coordinate lonlat respectively, [lon lat min(distance)]
Hope it works

类别

Help CenterFile Exchange 中查找有关 Legend 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by