Re: Euclidean distance [message #11637] |
Thu, 21 May 1998 00:00 |
Caesar E. Ordonez
Messages: 2 Registered: May 1998
|
Junior Member |
|
|
<HTML>
Imanol Echave wrote:
<BLOCKQUOTE TYPE=CITE>Hi:
<P> I'd like to program the following
routine: giving two set of vectors with n and
<BR>m vectors respectively (a matrix of size pxn and another of size pxm),
I want to
<BR>obtain a matrix of size nxm where the element (i,j) is the euclidean
distance
<BR>from first set's vector i to second set's vector j. I know the solution
using
<BR>loops, but exists it a different way without loops?</BLOCKQUOTE>
Here's my (quick and dirty) solution for two vectors.
<P> function edist, a, b
<BR> na = n_elements( a )
<BR> nb = n_elements( b )
<BR> ; print, na, nb
<BR> aa = a
<BR> bb = b
<BR> aa[*] = 1
<BR> bb[*] = 1
<BR> c1 = a^2#bb
<BR> c2 = aa#b^2
<BR> c = c1+c2
<BR> c = sqrt(c)
<BR> ;Check with loops
<BR> ;d=dblarr(na,nb)
<BR> ;for k=0,nb-1 do begin
<BR> ;for j=0,na-1 do begin
<BR> ; d[j,k]=sqrt(a[j]^2 + b[k]^2)
<BR> ;endfor
<BR> ;endfor
<BR> ;print,' '
<BR> ;print,c-d
<BR> return, c
<BR> end
<P>You can easily generalize to matrices by inserting code, before
<BR>the second line, that checks dimensions of a and b, and transforming
<BR>a and/or b to one-dimensional array via reform function.
<PRE>--
Caesar E. Ordonez, Ph.D.
Department of Medical Physics
Rush-Presbyterian-St. Luke's Medical Center
ordonez@spect2.rad.rpslmc.edu</PRE>
</HTML>
|
|
|