I have data in Stata with 3 variables, a string id and numeric variables (GPS data - latitude and longitude). I would like to convert the variables into a matrix in the following way (the lower table) to calculate the distance between two id-spots for all combinations. So a newly created subsequent column (e.g, id_1) has a subsequent(i+1) value of the original variable (e.g., id), and so on. However, the following command works only until the n-th row is reached to get a value; then the subsequent new rows become empty. Thus, the half bottom of the matrix gets missing (the upper table: ///) . For 2000 observations:
foreach num of numlist 1/2000 {
foreach var of varlist id num1 num2 {
gen `var'_`num'=`var'[_n+`num']
}
}

geonearfrom SSC. If you want travel distances, there are several existing community-contributed commands, e..gsearch distance. - Nick Coxwhatever[2001]or to values in later observations is legal but just returns missing as there is no such observation. - Nick Cox