Dav*_*ave 8 python arrays numpy scipy slice
我有两个阵列,A,B并希望在最后一个维度上采用外部产品,例如,
result[:,i,j]=A[:,i]*B[:,j]
当它A,B是二维的时.
如果我不知道它们是2维还是3维,我怎么能这样做呢?
在我的具体问题A,B中,是一个更大的三维数组中的切片Z,有时可以用整数索引调用,有时A=Z[:,1,:], B=Z[:,2,:]用切片调用A=Z[:,1:3,:],B=Z[:,4:6,:].由于scipy"挤压"单身尺寸,我不知道我的输入将是什么尺寸.
我想要定义的数组外部产品应该满足
array_outer_product( Y[a,b,:], Z[i,j,:] ) == scipy.outer( Y[a,b,:], Z[i,j,:] )
array_outer_product( Y[a:a+N,b,:], Z[i:i+N,j,:])[n,:,:] == scipy.outer( Y[a+n,b,:], Z[i+n,j,:] )
array_outer_product( Y[a:a+N,b:b+M,:], Z[i:i+N, j:j+M,:] )[n,m,:,:]==scipy.outer( Y[a+n,b+m,:] , Z[i+n,j+m,:] )
Run Code Online (Sandbox Code Playgroud)
对于任何rank-3数组Y,Z和整数a,b,...i,j,k...n,N,...
我正在处理的问题涉及二维空间网格,每个网格点都有一个矢量值函数.我希望能够在前两个轴上的切片定义的区域上计算这些矢量的协方差矩阵(外积).
在发现 numpy/scipy 数组中省略号的使用后,我最终将其实现为递归函数:
def array_outer_product(A, B, result=None):
''' Compute the outer-product in the final two dimensions of the given arrays.
If the result array is provided, the results are written into it.
'''
assert(A.shape[:-1] == B.shape[:-1])
if result is None:
result=scipy.zeros(A.shape+B.shape[-1:], dtype=A.dtype)
if A.ndim==1:
result[:,:]=scipy.outer(A, B)
else:
for idx in xrange(A.shape[0]):
array_outer_product(A[idx,...], B[idx,...], result[idx,...])
return result
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2610 次 |
| 最近记录: |