gpt4 book ai didi

python NumPy : how to construct a big diagonal array(matrix) from two small array

转载 作者:太空狗 更新时间:2023-10-29 20:23:47 28 4
gpt4 key购买 nike

import numpy as np

A = np.array([[1, 2],
[3, 4]])
B = np.array([[5, 6],
[7, 8]])

C = np.array([[1, 2, 0, 0],
[3, 4, 0, 0],
[0, 0, 5, 6],
[0, 0, 7, 8]])

我想直接从AB制作C,有什么简单的方法可以构造对角线数组C ?谢谢。

最佳答案

方法 #1: 一种简单的方法是使用 np.bmat -

Z = np.zeros((2,2),dtype=int) # Create off-diagonal zeros array
out = np.asarray(np.bmat([[A, Z], [Z, B]]))

sample 运行-

In [24]: Z = np.zeros((2,2),dtype=int)

In [25]: np.asarray(np.bmat([[A, Z], [Z, B]]))
Out[25]:
array([[1, 2, 0, 0],
[3, 4, 0, 0],
[0, 0, 5, 6],
[0, 0, 7, 8]])

方法#2:对于数组的通用数量,我们可以使用masking -

def diag_block_mat_boolindex(L):
shp = L[0].shape
mask = np.kron(np.eye(len(L)), np.ones(shp))==1
out = np.zeros(np.asarray(shp)*len(L),dtype=int)
out[mask] = np.concatenate(L).ravel()
return out

方法#3:对于通用数量的数组,另一种方法是 multi-dimensional slicing -

def diag_block_mat_slicing(L):
shp = L[0].shape
N = len(L)
r = range(N)
out = np.zeros((N,shp[0],N,shp[1]),dtype=int)
out[r,:,r,:] = L
return out.reshape(np.asarray(shp)*N)

样本运行-

In [137]: A = np.array([[1, 2], 
...: [3, 4]])
...: B = np.array([[5, 6],
...: [7, 8]])
...: C = np.array([[11, 12],
...: [13, 14]])
...: D = np.array([[15, 16],
...: [17, 18]])
...:

In [138]: diag_block_mat_boolindex((A,B,C,D))
Out[138]:
array([[ 1, 2, 0, 0, 0, 0, 0, 0],
[ 3, 4, 0, 0, 0, 0, 0, 0],
[ 0, 0, 5, 6, 0, 0, 0, 0],
[ 0, 0, 7, 8, 0, 0, 0, 0],
[ 0, 0, 0, 0, 11, 12, 0, 0],
[ 0, 0, 0, 0, 13, 14, 0, 0],
[ 0, 0, 0, 0, 0, 0, 15, 16],
[ 0, 0, 0, 0, 0, 0, 17, 18]])

In [139]: diag_block_mat_slicing((A,B,C,D))
Out[139]:
array([[ 1, 2, 0, 0, 0, 0, 0, 0],
[ 3, 4, 0, 0, 0, 0, 0, 0],
[ 0, 0, 5, 6, 0, 0, 0, 0],
[ 0, 0, 7, 8, 0, 0, 0, 0],
[ 0, 0, 0, 0, 11, 12, 0, 0],
[ 0, 0, 0, 0, 13, 14, 0, 0],
[ 0, 0, 0, 0, 0, 0, 15, 16],
[ 0, 0, 0, 0, 0, 0, 17, 18]])

关于 python NumPy : how to construct a big diagonal array(matrix) from two small array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42154606/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com