Hi all, greetings from Paris !
I am still developping my spatial tools under gretl, but I have a difficulty
with some matrix functions. My code is an adaptation of the "brute force"
find_neighbor of James LeSage.
Let me explain, I am given a list of coordinates for my data (spatial X and Y
location coordinates). The function is to find the k nearest neighbors of each
of my N data points.
The function computes for each of them a distance to all the others, then i
call a sort command to order the distances from smallest to largest to finally
extract the k smallest distances i am interested in (starting from line 2 to
k+1 because the lowest distance is zero, ie: the shortest distance to data i
is itself !).
Well, my problem is that I do not see how to grab not the values of sorted
distances but the indexes of data points. Here is the code :
matrix xc = X_COORD
matrix yc = Y_COORD
scalar n = rows(xc)
### i fix the number of near neighbors to 4, a typical value (rook neighborhood)
scalar m = 4
### I create a list of indexes of each of the 4 nearest neighbors set to zero
matrix nnlist = zeros(n,m)
### I added this dirty trick to keep track of the indexes I want to sort with
### the distances:
matrix idx = transp(seq(1,n))
### the main (brute force) loop
loop i = 1..n --quiet
matrix xi = xc[$i,1]
matrix yi = yc[$i,1]
matrix dist = sqrt((xc-xi*ones(n,1)).^2 + (yc - yi*ones(n,1)).^2)~idx
matrix xind = sort(dist[,1])
matrix nnlist[i,1:m] = transp(xind[2:m+1,1])
end loop
### I display the results to see the results
dist
xind
nnlist
As you can see, I compute a matrix dist holding distances concatenated with
indexes. Then i sort the distances and store them into the matrix xind. The
problem is that, I am not interested by the distances, but the indexes of the
units but xind only returns a vector of sorted distances and not the indexes.
In fact i would be interested in just extracting the values of indexes in the
sorted dist matrix. I do not understand how to use the command sort for
matrices.
any advice ?
thanx & cheers
Franck
PS: a text file with my (X,Y) data
--
Franck Nadaud
Economiste
CIRED
UMR 8568 CNRS - EHESS
45 bis avenue de la Belle Gabrielle
94736 Nogent-sur-Marne Cedex
TEL 33-1-43-94-73-94
FAX: 33-1-43-94-73-70
MOB: 06-07-39-92-75
France