Any faster way to calculate sphere distance between two tables of points?

1 view (last 30 days)
Hi guys,
I have been stuck recently. I'm trying to calculate distance between every point in table A and B, based on their longitudes and latitudes. However, my current solution is quite time-consuming and I think there must be a better way to solve it. With my limited Matlab knowledge, I haven't figured out a new implementation. The tables are shown as below, TableA (103376x6) and TableB (32x3):
I want to get the distance of each point of tableA to all the points in tableB. So the resulting matrix, dist, is a 103376 x 32 matrix. What I have done was to use two for loops, which is so inefficient with huge amount of data. So, how can I do to make it run faster? Appreciate your suggestions and comments.
for i=1:height(A)
for j=1:height(B)
dist(i,j) = distance(A.Lat(i),A.Lon(i),B.Lat(j),B.Lon(j))/180*pi*6378.137;
end
end
  4 Comments
Jess Lovering
Jess Lovering on 15 Aug 2019
Can you make 4 matrices that are each 103376 x 32 matrix (one for each of the lat1, lon1, lat2, lon2) and perform the distance calculation once? You could use the repmat command to replicate the lon in TableA 32 times and then repeat that for the lat. Then transpose the lat and lon arrays in TableB to be one row and 32 columns then repmat that 103376 times. Then you would have 4 matrices that are all 103376 x 32 that you could input to the distance command. Not sure what the time difference would be but I imagine it would be much faster.
QIAO WANG
QIAO WANG on 15 Aug 2019
That's a brilliant suggestion. Thank you Jessica. I spent some time trying to understand your point but once I understood it, it didn't take me too long to generate these matrices. And your expectation was right. It is now much much faster, just 1 sec.

Sign in to comment.

Answers (0)

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!