# st: RE: Matrix manipulation help

 From "Nick Cox" To Subject st: RE: Matrix manipulation help Date Wed, 13 May 2009 19:08:31 +0100

```You don't say what "didn't work" means to you, but I can spot various
problems.

This mixes Stata [NB spelling] and Mata code without flagging that you
are entering Mata etc. You can't be so casual. See any introduction to
Mata for more details. So, for example, Mata can't see the scalar N in
Stata unless you pass it explicitly or otherwise make it visible. You've
got a lot of reading to do. As Euclid would have said, there is no royal

By the way, you are not obliged to use Mata. You can use Stata for
matrix looping, but you must then use -forval- not -for-.

Your distance formula is incorrect and in any case your parentheses are
not balanced:

((xcoord[i]-xcoord[j]^2+(ycoord[i]-ycoord[j]^2)^0.5

should be

((xcoord[i]-xcoord[j])^2+(ycoord[i]-ycoord[j])^2)^0.5

In fact I would use -sqrt()- rather than call up the general powering
routine. I have a sneaking suspicion that's faster.

sqrt((xcoord[i]-xcoord[j])^2+(ycoord[i]-ycoord[j])^2)

As another matter of efficiency, after initialising your distance matrix
to zeros, you can go

for(i = 1; i <=N; i++) {
for(j = 1; j < i; j++) {
D[i,j] = <as above>
D[j,i] = D[i,j]
}
}

That way,

1. The test for equal i and j is avoided as unnecessary.
2. You exploit the identity D[i,j] = D[j,i] (the distance between A and
Bk is the distance between B and A).

By the way, hasn't this been done before?

Nick
n.j.cox@durham.ac.uk

Susan Olivia

Can I get programming advice how to create a NxN distance
matrix using the information on latitude and longitude.

Below is what I attempted to do in STATA, but it didn't
work. Would be great if I can get any advice on how to
improve this code.

****************************
qui set obs 1000

gen xcoord = uniform()*100
gen ycoord = uniform()*100

mkmat xcoord ycoord

local N=_N
scalar N = _N

matrix latlong= xcoord,ycoord

matrix D = J(`N',`N', 0)

* looping through the rows and columns of the matrix D, to
get distance pair for each observations

for(i = 1; i <=N; i++) {
for(j = 1; j<=N; j++) {
if (i!=j){
D[i,j]=
((xcoord[i]-xcoord[j]^2+(ycoord[i]-ycoord[j]^2)^0.5

}
}
}

*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/
```