0

I am new to python and need to do the following thing:

I've given an 1d array of vectors (so pretty much 2d).

My task is to create an 1d array that contains the length of each vector.

array([[0.  , 0.  ],
   [1.  , 0.  ],
   [1.  , 1.  ],
   [1.  , 0.75],
   [0.75, 1.  ],
   [0.5 , 1.  ]
   ...

should be converted to

array([0,
   1,
   1.4142,
   ...

I could easily do this in theory but I am not familiar with the inbuild commands of python and I am very happy if someone could tell me some inbuild commands of python that can do this.

jpp
  • 159,742
  • 34
  • 281
  • 339
Finn Eggers
  • 857
  • 8
  • 21

6 Answers6

4

Using norm from np.linalg.norm:

import numpy as np

a = np.array([[0., 0.],
              [1., 0.],
              [1., 1.],
              [1., 0.75],
              [0.75, 1.],
              [0.5, 1.]])

print(np.linalg.norm(a, axis=1))

Output

[0.         1.         1.41421356 1.25       1.25       1.11803399]
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
3

With NumPy you can use vectorised operations:

A = np.array([[0.  , 0.  ],
              [1.  , 0.  ],
              [1.  , 1.  ],
              [1.  , 0.75],
              [0.75, 1.  ],
              [0.5 , 1.  ]])

res = np.sqrt(np.square(A).sum(1))

array([ 0.        ,  1.        ,  1.41421356,  1.25      ,  1.25      ,
        1.11803399])

Alternatively, if you prefer a less functional solution:

res = (A**2).sum(1)**0.5
jpp
  • 159,742
  • 34
  • 281
  • 339
1

You can use the list comprehension. In Python 2,

print [(x[0]*x[0]+x[1]*x[1])**0.5 for x in arr]

where arr is your input

pfctgeorge
  • 698
  • 3
  • 9
1

You can try this:

import math
b = []
for el in arr:
    b.append(math.sqrt(el[0]**2 + el[1]**2))

print b

or you can do it even shorter:

b = [math.sqrt(el[0]**2 + el[1]**2) for el in arr]

where arr is the your array.

Here is and one more example with lambda:

b = map(lambda el: (el[0]**2 + el[1]**2)**0.5, arr)
dim
  • 992
  • 11
  • 26
1

you can iterate over your array to find the vector length:

array=[[0,0],[0,1],[1,0],[1,1]]
empty=[]
for (x,y) in array:
    empty.append((x**2+y**2)**0.5)
print(empty)
Newmsy
  • 13
  • 3
1

You can achieve it with hypotenuse np.hypot

np.hypot(array[:, 0], array[:, 1])
taras
  • 6,566
  • 10
  • 39
  • 50