Numpy symmetric 4D matrix construction

感情迁移 提交于 2021-02-10 06:38:15

问题


I would like to construct an array with the following structure:

A[i,j,i,j,] = B[i,j] with all other entries 0: A[i,j,l,k]=0 # (i,j) =\= (l,k)

I.e. if I have the B matrix constructed how can I create the matrix A, preferably in a vectorized manner.

Explicitly, let B = [[1,2],[3,4]]

Then:

A[1,1,:,:]=[[1,0],[0,0]]
A[1,2,:,:]=[[0,2],[0,0]]
A[2,1,:,:]=[[0,0],[3,0]]
A[2,2,:,:]=[[0,0],[0,4]]

回答1:


We can use an open grid to assign to A broadcasting the indexing arrays across the axes:

B = np.array([[1,2],[3,4]])
i,j = B.shape
A = np.zeros([i,j,i,j])
i, j = np.ogrid[:i, :j]
A[i,j,i,j] = B

print(A)

array([[[[1., 0.],
         [0., 0.]],

        [[0., 2.],
         [0., 0.]]],


       [[[0., 0.],
         [3., 0.]],

        [[0., 0.],
         [0., 4.]]]])



回答2:


This is my solution with indexing:

x,y = np.meshgrid(np.arange(B.shape[1]),np.arange(B.shape[0]))
x,y = x.ravel(), y.ravel()

A = np.zeros(B.shape + B.shape)

A[y.ravel(), x.ravel(), y.ravel(), x.ravel()] = B.ravel()

# checking
for i in range(2):
    for j in range(2):
        print(f'A[{i},{j}]:',A[i,j])

Output:

A[0,0]: [[1. 0.]
 [0. 0.]]
A[0,1]: [[0. 2.]
 [0. 0.]]
A[1,0]: [[0. 0.]
 [3. 0.]]
A[1,1]: [[0. 0.]
 [0. 4.]]


来源:https://stackoverflow.com/questions/61826786/numpy-symmetric-4d-matrix-construction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!