【问题标题】:how to set diagonal of volume of matrices in numpy?如何在numpy中设置矩阵体积的对角线?
【发布时间】:2022-01-05 01:35:31
【问题描述】:

我有很多矩阵,比如a = np.zeros((5, 7, 4, 4))

我想将所有矩阵的对角线设置为某个值。

就像我可以 get the diagonaldiag = np.diagonal(a, axis1=2, axis2=3) 一样,我想设置对角线。

但是,np.fill_diagonal 不支持axis=

我怎样才能做到这一点?

【问题讨论】:

  • 你能用循环来做吗,或者你正在寻找一个内置的解决方案?
  • @ofey 循环对我没有好处。
  • fill_diagonal 适用于 4d 数组。首先转置轴。

标签: python numpy


【解决方案1】:

你可以这样做:

s1, s2, s3, s4 = a.shape
i, j = np.diag_indices(s3)  # s3 == s4 == 4 here.
a[..., i, j] = 3

【讨论】:

    【解决方案2】:
    import numpy as np
    
    a = np.zeros((5, 7, 4, 4))
    s0, s1, s2, s3 = a.shape
    
    for index in range(s0):
        a[index].reshape(s1,-1)[:,::s3+1] = 3 # assign the diagonal values to 3
    

    取自fast way to set diagonals of an M x N x N matrix,稍作改动。我相信这可以满足您的需求。

    编辑:啊哈。正如@hpaulj 所建议的那样,我们可以按照您的意愿在没有循环的情况下完成。

    a = np.zeros((5, 7, 4, 4))
    s0, s1, s2, s3 = a.shape
    a.reshape(s0 * s1, -1)[:,::s3+1] = 3 # assign the diagonal values to 3
    

    【讨论】:

    • 您应该能够在没有循环的情况下将链接的答案应用于 4d。
    • @hpaulj 感谢您的想法。只是“扁平化”它甚至可以更好地工作:)
    猜你喜欢
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 2012-04-15
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    相关资源
    最近更新 更多