如何在numpy中创建对角线多维(即大于2)

Riv*_*tya 6 numpy

是否有更高(大于两个)维度的 diag 等价物?

L = [...] # some arbitrary list.
A = ndarray.diag(L)
Run Code Online (Sandbox Code Playgroud)

将创建一个对角线二维矩阵 shape=(len(L), len(L)) 在对角线上具有 L 元素。

我想做相当于:

length = len(L)
A = np.zeros((length, length, length))
for i in range(length):
    A[i][i][i] = L[i]
Run Code Online (Sandbox Code Playgroud)

有没有一种巧妙的方法来做到这一点?

谢谢!

tom*_*m10 5

您可以使用diag_indices来获取要设置的索引。例如,

x = np.zeros((3,3,3))
L = np.arange(6,9)

x[np.diag_indices(3,ndim=3)] = L
Run Code Online (Sandbox Code Playgroud)

array([[[ 6.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],

       [[ 0.,  0.,  0.],
        [ 0.,  7.,  0.],
        [ 0.,  0.,  0.]],

       [[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  8.]]])
Run Code Online (Sandbox Code Playgroud)

引擎盖diag_indices下只是 Jaime 发布的代码,因此使用哪个取决于您是希望它在 numpy 函数中拼写出来,还是 DIY。