简体   繁体   English

迭代和访问numpy数组元素的最快方法?

[英]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. 我正在尝试实现一个MATLAB代码,它使用数组的向量化迭代和访问元素。 Code snippet is below: 代码段如下:

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

where "z" is an array containing I/Q stream value ie alternating i & q like "iqiqiqiq...". 其中“z”是包含I / Q流值的数组,即交替i&q,如“iqiqiqiq ...”。 I am trying to implement it using numpy array but with no success. 我试图使用numpy数组实现它,但没有成功。

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. 注意:还要寻找有关实现上述逻辑的任何其他方法的建议,这比使用numpy数组和python-3.x复制MATLAB方法更快。

If z is a numpy array of 64 bit floating points values, and the data in z is contiguous (eg you didn't form z by slicing it from a bigger array), you can create a complex view of z with no copying : 如果z是64位浮点值的numpy数组,并且z的数据是连续的(例如,您没有通过从更大的数组中切片来形成z ),则可以创建z的复杂视图 而不进行复制

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. 为了完整起见,这里是您的Matlab代码更直接(也更低效)的翻译。 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.) (我用len(z)//2表示w的大小。这假设z是一维数组。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM