Shan
Shan

Reputation: 19243

Vectorizing a function using numpy vectorize

I want to vectorize the following function. The arguments are numpy arrays.

def euclidean_distance(dl, dr):
    return math.sqrt(((dl - dr) ** 2).sum())

I do the following

v_u = numpy.vectorize(euclidean_distance)

and I am doing the following call

v_u(numpy.array([[10, 20, 30], [4, 5, 6]]), numpy.array([1, 2, 3]))

What I want is that I get back an array which contains the euclidean distance of [1, 2, 3] with [10, 20, 30], [4, 5, 6].

I think I am missing something obvious.

EDIT:
The following is the error I get

AttributeError: 'int' object has no attribute 'sum'

which is obvious that dl and dr are passed as single elements but not as arrays... So I was wondering if somebody could correct it so that it operated on arrays.

Thanks a lot

Upvotes: 1

Views: 464

Answers (1)

Andrey Sobolev
Andrey Sobolev

Reputation: 12673

Why do you need vectorize for that?

You can use shape broadcasting and do something like:

dist = numpy.sqrt(numpy.sum((d1-dr)**2, axis = 1))

Upvotes: 5

Related Questions