1

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.

1 Answer 1

4

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.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.