# [Numpy-discussion] Distance Formula on an Array

josef.pktd@gmai... josef.pktd@gmai...
Sat Apr 25 15:00:41 CDT 2009

```On Sat, Apr 25, 2009 at 3:57 PM, Charles R Harris
<charlesr.harris@gmail.com> wrote:
>
>
> On Sat, Apr 25, 2009 at 12:50 PM, Ian Mallett <geometrian@gmail.com> wrote:
>>
>> Hi,
>>
>> I have an array sized n*3.  Each three-component is a 3D position.  Given
>> another 3D position, how is the distance between it and every
>> three-component in the array found with NumPy?
>>
>> So, for example, if the array is:
>> [[0,0,0],[0,1,0],[0,0,3]]
>> And the position is:
>> [0,4,0]
>> I need this array out:
>> [4,3,5]
>> (Just a simple Pythagorean Distance Formula)
>
> In [3]: vec = array([[0,0,0],[0,1,0],[0,0,3]])
>
> In [4]: pos = array([0,4,0])
>
> In [5]: sqrt(((vec - pos)**2).sum(1))
> Out[5]: array([ 4.,  3.,  5.])
>

if scipy is permitted:

>>> a = np.array([[0,0,0],[0,1,0],[0,0,3]])
>>> scipy.spatial.distance_matrix(a, [[0,4,0]])
array([[ 4.],
[ 3.],
[ 5.]])
>>> scipy.spatial.minkowski_distance(a, [0,4,0])
array([ 4.,  3.,  5.])

Josef
```