从没有for循环的二维矩阵的行创建对角矩阵

时间:2021-01-31 02:51:35

标签: python numpy vectorization numpy-ndarray diagonal

假设您有一个 mxn 矩阵 A 并且想要创建 m 个对角矩阵,每个对角矩阵都来自 A 的行,因此形状为 nxn。结果矩阵的形状应为 mxnxn

我知道一个典型的解决方案是:

result = numpy.stack([numpy.diag(A[i,:]) for i in range(A.shape[0])], axis=0)

我想知道是否有可能在不使用循环的情况下获得相同的结果。

任何想法将不胜感激!

3 个答案:

答案 0 :(得分:1)

这似乎有效:

   acc.onclick = function () {
        const accdropDisplayValue = window.getComputedStyle(accdrop)
                                          .getPropertyValue('display');

         if (accdropDisplayValue === "none") {
             accdrop.style.display = "block";
         }
    }

测试输入:

result = np.zeros((A.shape[0], A.shape[1], A.shape[1]), dtype=A.dtype)
result[:, range(A.shape[1]), range(A.shape[1])] = A

A = np.arange(24).reshape(4,6) 的输出:

print(result)

答案 1 :(得分:0)

这不会是最有效的方法,但这样的方法可能会奏效

import numpy as np

A = np.random.rand(10, 5)

S = np.einsum("ai,ij->aij", A, np.ones((5, 5)))
M = np.eye(5).astype(np.bool)
M = np.repeat(M[None, ...], 10, axis=0)
S[~M]=0
print(S.shape)

答案 2 :(得分:0)

您可以尝试以下方法,我们使用 broadcastingnumpy.identity() 来获得所需的结果。

# `arr` is input of size (m, n); for instance,
arr = np.arange(1, 13).reshape(3, -1)   # (3, 4)

# get column size
In [160]: _ , n = arr.shape

# fill the rows from the input, after promoting it to 3D
In [161]: res = np.eye(n, dtype=arr.dtype) * arr[:,np.newaxis]

In [162]: res.shape
Out[162]: (3, 4, 4)

注意:由于我们将 (n,n) 作为最后两个维度,因此 np.identity() 也可以使用。

In [171]: res = np.identity(n, dtype=arr.dtype) * arr[:,np.newaxis]

In [172]: res.shape
Out[172]: (3, 4, 4)

另一种方法是使用 advanced indexing,其中首先用零初始化结果数组并切出对角元素的索引并用输入数组填充它们。