将函数广播到3D数组Python [英] Broadcasting a function to a 3D array Python
问题描述
我尝试了解使用3d数组进行numpy广播,但我认为这里有OP问一些稍有不同的东西。
I tried understanding numpy broadcasting with 3d arrays but I think the OP there is asking something slightly different.
我有一个像这样的3D numpy数组-
I have a 3D numpy array like so -
IQ = np.array([
[[1,2],
[3,4]],
[[5,6],
[7,8]]
], dtype = 'float64')
此数组的形状为(2,2,2)。我想对3D矩阵中的每个1x2数组应用一个函数,像这样-
The shape of this array is (2,2,2). I want to apply a function to each 1x2 array in this 3D matrix like so -
def func(IQ):
I = IQ[0]
Q = IQ[1]
amp = np.power((np.power(I,2) + np.power(Q, 2)),1/2)
phase = math.atan(Q/I)
return [amp, phase]
如您所见,我想将我的函数应用于每个1x2数组,并将其替换为函数的返回值。输出是具有相同尺寸的3D阵列。有没有办法将此功能广播到原始3D阵列中的每个1x2阵列?当前,我使用的循环会随着3D数组尺寸的增加而变得非常慢。
As you can see, I want to apply my function to each 1x2 array and replace it with the return value of my function. The output is a 3D array with the same dimensions. Is there a way to broadcast this function to each 1x2 array in my original 3D array? Currently I am using loops which becomes very slow as the 3D array increases in dimensions.
当前,我正在这样做-
#IQ is defined from above
for i in range(IQ.shape[0]):
for j in range(IQ.shape[1]):
I = IQ[i,j,0]
Q = IQ[i,j,1]
amp = np.power((np.power(I,2) + np.power(Q, 2)),1/2)
phase = math.atan(Q/I)
IQ[i,j,0] = amp
IQ[i,j,1] = phase
返回的3D数组是-
[[[ 2.23606798 1.10714872]
[ 5. 0.92729522]]
[[ 7.81024968 0.87605805]
[10.63014581 0.85196633]]]
推荐答案
一种方法是对数组进行切片以提取I和Q值,使用常规广播执行计算,然后将这些值重新粘贴在一起:
One way is to slice the arrays to extract the I and Q values, perform the computations using normal broadcasting, and then stick the values back together:
>>> Is, Qs = IQ[...,0], IQ[...,1]
>>> np.stack(((Is**2 + Qs**2) ** 0.5, np.arctan2(Qs, Is)), axis=-1)
array([[[ 2.23606798, 1.10714872],
[ 5. , 0.92729522]],
[[ 7.81024968, 0.87605805],
[10.63014581, 0.85196633]]])
这篇关于将函数广播到3D数组Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!