【问题标题】:3D tensor of diagonal matrices对角矩阵的 3D 张量
【发布时间】:2021-04-24 10:37:37
【问题描述】:

我有一个 m 行 n 列的矩阵 A。我想要一个维度为 m*n*n 的 3D 张量,使得张量由 A 的每一列形成的 m 个对角矩阵组成。换句话说,A 的每一列都应该转换为对角化矩阵,所有这些矩阵都应该一起形成一个 3D 张量。

使用 for 循环很容易做到这一点。但我想在不提高速度的情况下这样做。

我想出了一个糟糕且低效的方法,但我希望有人能帮助我找到更好的方法,它允许大型 A 矩阵。

# I use python
# import numpy as np
n = A.shape[0] # A is an n*k matrix
k = A.shape[1]

holding_matrix = np.repeat(np.identity(k), repeats=n, axis=1) # k rows with n*k columns
identity_stack = np.tile(np.identity(n),k) #k nxn identity matrices stacked together

B = np.array((A@holding_matrix)*identity_stack)
B = np.array(np.hsplit(B,k)) # desired result of k n*n diagonal matrices in a tensor

【问题讨论】:

  • 欢迎来到 Stack Overflow!我认为这个问题更适合codereview.stackexchange.com,因为它处理的是可以改进的工作代码。

标签: python numpy matrix algebra


【解决方案1】:
n = A.shape[0] # A.shape == (n, k)
k = A.shape[1]

B = np.zeros_like(A, shape=(k, n*n)) # to preserve dtype and order of A

B[:, ::(n+1)] = A.T
B = B.reshape(k, n, n)

【讨论】:

    猜你喜欢
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 2011-05-28
    • 2021-11-12
    • 2017-08-10
    • 2018-11-16
    • 2019-12-03
    相关资源
    最近更新 更多