Created
March 20, 2012 21:07
-
-
Save alexstorer/2141305 to your computer and use it in GitHub Desktop.
Vectorized Distance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The vectorized way performs between 10 and 100 times faster on my macbook pro.