On Thu, 8 Jul 2010 06:11:37 -0700 (PDT), Fabzi
<fabien.maussion@gmail.com> wrote:
> After using a long time the (very) inefficient "for loop":
>
> -----
> n2 = N_ELEMENTS(x2)
> for i = 0l, n2 - 1 do begin
> quad = (x2[i] - x1)^2 + (y2[i]- y1)^2
> minquad = min(quad, p)
> if N_ELEMENTS(p) gt 1 then p = p[0] ; it happens.....
> out[i] = p
> endfor
> ---
>
> I finaly found the best solution:
>
> ---
> n1 = n_elements(ilon)
> triangulate, x1, y1, c ; Compute Delaunay triangulation
> out = GRIDDATA(x1,y1, LINDGEN(n1), XOUT=x2, YOUT=y2, /NEAREST_N,
> TRIANGLES =c)
> ---
These two methods give a different result. Try running the code below.
The red and green lines connect the nearest neighbours from method 1
and method 2. You should see only red lines, but you see some green
lines too...
This doesn't answer your question about finding the 4 closest
neighbours however. Couldn't you use griddata with bilinear
interpolation and get the "4 corners" from the interpolated value?
I'll think about it :-).
The real question is, what are you going to do when you have the 4
nearest neighbours? What are you trying to achieve that can't be done
with IDL's gridding and interpolation routines?
pro ConnectGrids
; First grid
n1 = 100
seed = -121147L
x1 = round(RANDOMU(seed, n1)*n1)
y1 = round(RANDOMU(seed, n1)*n1)
; Second grid
n2 = 100
x2 = round(RANDOMU(seed, n2)*n2)
y2 = round(RANDOMU(seed, n2)*n2)
; Find closest: method 1
triangulate, x1, y1, c ; Compute Delaunay triangulation
iconnect = GRIDDATA(x1,y1, LINDGEN(n1), Xout=x2, Yout=y2,$
/NEAREST_N,TRIANGLES =c)
; Find closest: method 2
iconnect2=iconnect
for i=0l,n2-1 do begin
tmp=min((x2[i]-x1)^2.+(y2[i]-y1)^2.,ind)
iconnect2[i]=ind[0]
endfor
; Plot result
device,decompose=0
loadct,39
window
n=n1>n2
plot,x1,y1,psym=1,xrange=[-10,n+9],yrange=[-10,n+9],/xs,/ys
oplot,x2,y2,psym=1,color=100
for i=0,n2-1 do
plots,[x1[iconnect[i]],x2[i]],[y1[iconnect[i]],y2[i]],color= 150
for i=0,n2-1 do plots,$
[x1[iconnect2[i]],x2[i]],[y1[iconnect2[i]],y2[i]],color=250
end
|