Jay Krishna
Jay Krishna

Reputation: 23

Fastest way of iterating and accessing elements of numpy array?

I am trying to implement a MATLAB code which is iterating and accessing elements using vectorization of array. Code snippet is below:

z=z(1:2:end)+j*z(2:2:end);

where "z" is an array containing I/Q stream value i.e alternating i & q like "iqiqiqiq...". I am trying to implement it using numpy array but with no success.

Note: Also looking for suggestions regarding any other way to implement the above logic which is even faster than copying MATLAB approach using numpy array and python-3.x.

Upvotes: 1

Views: 355

Answers (1)

Warren Weckesser
Warren Weckesser

Reputation: 114811

If z is a numpy array of 64 bit floating points values, and the data in z is contiguous (e.g. you didn't form z by slicing it from a bigger array), you can create a complex view of z with no copying:

In [56]: z
Out[56]: array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.])

In [57]: z.view(np.complex128)
Out[57]: array([ 0.+1.j,  2.+3.j,  4.+5.j,  6.+7.j,  8.+9.j])

For completeness, here is the more direct (and less efficient) translation of your Matlab code. It produces a copy:

In [63]: z[::2] + z[1::2]*1j
Out[63]: array([ 0.+1.j,  2.+3.j,  4.+5.j,  6.+7.j,  8.+9.j])

A more verbose but more efficient method to create a copy is:

In [73]: w = np.empty(len(z)//2, dtype=np.complex128)

In [74]: w.real = z[::2]

In [75]: w.imag = z[1::2]

In [76]: w
Out[76]: array([ 0.+1.j,  2.+3.j,  4.+5.j,  6.+7.j,  8.+9.j])

(I used len(z)//2 for the size of w. This assumes z is a one-dimensional array.)

Upvotes: 4

Related Questions