NewToPython
NewToPython

Reputation: 13

How to perform a vectorized function on a 2D numpy array?

vecs = np.array([[1, 2, 3],
                 [4, 5, 6],
                 [7, 8, 9]])

def find_len(vector):
    return (vector[0] ** 2 + vector[1] ** 2 + vector[2] ** 2) ** 0.5

vec_len = np.vectorize(find_len)

I want to apply find_len to every vector in the 2d array and create a new numpy array with the values returned. How can I do this?

Upvotes: 1

Views: 336

Answers (2)

Hu gePanic
Hu gePanic

Reputation: 110

try this

res= []
for i in range(vecs.shape[0]):
    res.append(find_len(vecs[i]))
res=np.array(res)

results in

array([ 3.74165739,  8.77496439, 13.92838828])

you can also make this in one line:

res = np.array([find_len(x) for x in vecs[range(vecs.shape[0])]])

Upvotes: 1

Kraigolas
Kraigolas

Reputation: 5560

Are you just looking for this result:

array([ 3.74165739,  8.77496439, 13.92838828])

because you can achieve that without vectorize, just use:

(vecs**2).sum(axis=1)**0.5

This also has the advantage of not being specific to vectors of length 3.


Operations are already applied element-wise, so you can handle the squaring and square rooting normally. sum(axis=1) says to sum along the rows.

Upvotes: 1

Related Questions