﻿ Python NumPy: Find point by point distances of a random vector with shape (10,2) representing coordinates - w3resource

# Python: Find point by point distances of a random vector with shape (10,2) representing coordinates

## Python NumPy: Random Exercise-12 with Solution

Write a Python program to find point by point distances of a random vector with shape (10,2) representing coordinates.

Sample Solution :-

Python Code :

``````import numpy as np
a= np.random.random((10,2))
x,y = np.atleast_2d(a[:,0], a[:,1])
d = np.sqrt( (x-x.T)**2 + (y-y.T)**2)
print(d)
``````

Sample Output:

```[[ 0.          0.42309206  0.59799949  0.44076341  0.64568848  0.53547789
0.39263926  0.38982854  0.39228612  0.44529689]
[ 0.42309206  0.          1.0208224   0.38421553  0.92200913  0.73182405
0.73513877  0.80796679  0.64687549  0.73308548]
[ 0.59799949  1.0208224   0.          0.94341451  0.66895368  0.71852306
0.48605697  0.22453123  0.64173589  0.55440442]
[ 0.44076341  0.38421553  0.94341451  0.          0.60846866  0.9467662
0.51350109  0.78044594  0.36885259  0.88113793]
[ 0.64568848  0.92200913  0.66895368  0.60846866  0.          1.12199998
0.27042981  0.66189707  0.27709162  0.98097303]
[ 0.53547789  0.73182405  0.71852306  0.9467662   1.12199998  0.
0.85159212  0.53429835  0.90830578  0.1651062 ]
[ 0.39263926  0.73513877  0.48605697  0.51350109  0.27042981  0.85159212
0.          0.41507505  0.16091134  0.71215345]
[ 0.38982854  0.80796679  0.22453123  0.78044594  0.66189707  0.53429835
0.41507505  0.          0.54198973  0.370672  ]
[ 0.39228612  0.64687549  0.64173589  0.36885259  0.27709162  0.90830578
0.16091134  0.54198973  0.          0.78707458]
[ 0.44529689  0.73308548  0.55440442  0.88113793  0.98097303  0.1651062
0.71215345  0.370672    0.78707458  0.        ]]
```

Python Code Editor:

```import numpy as np
a= np.random.random((10,2))
x,y = np.atleast_2d(a[:,0], a[:,1])
d = np.sqrt( (x-x.T)**2 + (y-y.T)**2)
print(d)```

Improve this sample solution and post your code through Disqus