Statalist The Stata Listserver


[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

Re: st: RE: Latitude, Longitude and distances


From   [email protected]
To   [email protected]
Subject   Re: st: RE: Latitude, Longitude and distances
Date   Wed, 30 Aug 2006 13:31:57 -0500

In addition to the other suggestions, here are two ways to calculate 
the distance between 30 locations: using Stata directly or using 
Mata.  The results are stored as an additional 30 variables or as a 
Mata matrix.

Scott

clear
set obs 30
gen id =_n
set seed 1234
gen latitude = 10*uniform()
gen longitude = 10*uniform()

///Mata  
mata
X= st_data(.,( "latitude" , "longitude"))
X =X*(pi()/180)
km = J(rows(X),rows(X), 0)
for (i = 1; i <=rows(X); i++) {
    for (j = 1; j <=rows(X); j++) {
	  km[i,j] = 6372.795*(2*asin(sqrt( sin((X[i,1] /// 
	  - X[j,1])/2)^2 +  cos(X[i,1])*cos(X[j,1])*sin((X[i,2] ///
	  - X[j,2])/2)^2  )))
	  miles = km*(1/1.609)
	  furlongs = miles/8
     }
}
end

//Stata
qui levelsof id, local(level1)
replace lati = (_pi/180)*lati
replace longi = (_pi/180)*longi

foreach l1 of local level1 {
	qui gen dist_to_`l1' = .
}

local i = 1
foreach l1 of local level1 {
   local j = 1
      foreach l2 of local level1 {
         qui replace dist_to_`l2' = 6372.795*(2*asin(sqrt( /// 
	 sin((lati[`i'] - lati[`j'])/2)^2 ///
	 + cos(lati[`i'])*cos(lati[`j'])*sin((longi[`i'] ///
	 - longi[`j'])/2)^2  ))) in `i'
	 local ++j
      }
local ++i
}


*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index