Skip to content

Instantly share code, notes, and snippets.

@alexstorer
Created March 20, 2012 21:07
Show Gist options
  • Save alexstorer/2141305 to your computer and use it in GitHub Desktop.
Save alexstorer/2141305 to your computer and use it in GitHub Desktop.
Vectorized Distance
%d=6378.1*acos(sin(2*pi*lat(i)/360)*sin(2*pi*lat(j)/360)+cos(2*pi*(lng(i)-lng(j))/360)*cos(2*pi*lat(i)/360)*cos(2*pi*lat(j)/360));
tic
N = 4000;
% test some distances
lat = rand(N,1)*180;
lng = rand(N,1)*180;
% the loopy way
d = zeros(N);
dnew = d;
toc
for i = 1:N
for j = 1:N
d(i,j)=6378.1*acos(sin(2*pi*lat(i)/360)*sin(2*pi*lat(j)/360)+cos(2*pi*(lng(i)-lng(j))/360)*cos(2*pi*lat(i)/360)*cos(2*pi*lat(j)/360));
end
end
toc
% the vectorized way
tic
latrad = 2*pi*lat/360;
lngrep = repmat(lng,1,N);
d1 = sin(latrad)*sin(latrad)';
lngscale = cos(2*pi*(lngrep-lngrep')/360);
d2 = lngscale.*(cos(latrad)*cos(latrad)');
dnew = 6378.1*acos(d1+d2);
toc
@alexstorer
Copy link
Author

The vectorized way performs between 10 and 100 times faster on my macbook pro.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment