Oliver Amundsen
Oliver Amundsen

Reputation: 1511

Calculate great circle distance of all matrix elements to all matrix elements

I have the following vector of coordinates

LL = [lat lon]; % 5000 x 2

And I want to calculate the distances of all the elements to all elements using:

[dist, ~] = deg2km(distance[lat1, lon1, lat2, lon2]);

so the final matrix would be, I guess, 5000x5000. BTW the function distance comes in the Mapping toolbox. I tried a loop one-by-one, but it takes centuries to run.

UPDATE

LL = 
    -79.49583374               40.029166991
    -79.50416707               40.029166991
    -79.50416707               40.037500324

D = pdist(LL, @(x2,x1)(deg2km(distance(x1(1),x1(2),x2(1),x2(2)))))
D =
          2014.58795578131          2014.58795578131         0.168797611011563

while just for the first 2 coordinates:

D = deg2km(distance(LL(1,2),LL(1,1),LL(2,2),LL(2,1)))
D =
         0.709531880098433

----

Any help please?

Upvotes: 0

Views: 185

Answers (2)

Dan
Dan

Reputation: 45752

I didn't realise distance was a Matlab function, sorry. Try this:

D = pdist(LL, @(x1,x2) (distance(x1(:,1),x1(:,2),x2(:,1),x2(:,2))))

What does @(x1,x2) (distance(x1(:,1),x1(:,2),x2(:,1),x2(:,2))) do?

It's an anonymous function that expects two inputs, x1 and x2, and each should be n-by-2. For now let's pretend n equals 1. So pdist will give our anonymous function every different pair of rows from LL as inputs x1 and x2. A row from LL is of the form [lat, lon] and we are getting two such rows. We know that distance requires distance(lat1,lon1,lat2,lon2). So if x1 is a row of LL then it's [lat1, lon1] so x1(1) is actually lat1 and x1(2) is actually lon2. Same with x2 and [lat2,lon2].

So all our anonymous function is doing is converting distance from a function taking 4 inputs, into a much more standard formed Matlab distance function that accepts only 2 inputs.

EDIT:

As you are swapping latitudes and longitudes, this might work for you:

D = pdist(LL, @(x1,x2) (distance(x1(:,2),x1(:,1),x2(:,2),x2(:,1))))

Upvotes: 3

dlavila
dlavila

Reputation: 1212

Try this:

D = pdist2(LL,LL, @distfun);

Upvotes: 1

Related Questions