TheGrapeBeyond
TheGrapeBeyond

Reputation: 563

Vectorized example of the math.atan2() function in python

let us say I have a numpy matrix A that is of size Nx2. What I am doing, is computing the 4-quadrant inverse tangent of the first column, and the second column, as so:

import math
for i in xrange(A.shape[0]):
  phase[i] = math.atan2(A[i,0], A[i,1])

I would however like to do this in a vectorized manner. How can I do that? The math.atan2() function does not seem to support vectorization.

Thanks!

Upvotes: 0

Views: 2761

Answers (1)

mgilson
mgilson

Reputation: 309929

It looks to me like it should just be:

import numpy as np
phase = np.arctan2(A[:, 0], A[:, 1])

Or possibly (if phase is a different length than A for some odd reason):

phase[:len(A)] = np.arctan2(A[:, 0], A[:, 1])

In other words, don't use math.atan2, use numpy.arctan2 since numpy functions are generally vectorized versions of their math counterparts.

Upvotes: 6

Related Questions