【问题标题】:Python — How can I find the square matrix of a lower triangular numpy matrix? (with a symmetrical upper triangle)Python — 如何找到下三角 ​​numpy 矩阵的方阵? (带有对称的上三角形)
【发布时间】:2013-06-30 22:17:03
【问题描述】:

我生成了一个下三角矩阵,我想用下三角矩阵中的值完成矩阵,形成一个方阵,围绕对角线零点对称。

lower_triangle = numpy.array([
[0,0,0,0],
[1,0,0,0],
[2,3,0,0],
[4,5,6,0]])

我想生成以下完整矩阵,保持零对角线:

complete_matrix = numpy.array([
[0, 1, 2, 4],
[1, 0, 3, 5],
[2, 3, 0, 6],
[4, 5, 6, 0]])

谢谢。

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    你可以简单地将它添加到它的转置中:

    >>> m
    array([[0, 0, 0, 0],
           [1, 0, 0, 0],
           [2, 3, 0, 0],
           [4, 5, 6, 0]])
    >>> m + m.T
    array([[0, 1, 2, 4],
           [1, 0, 3, 5],
           [2, 3, 0, 6],
           [4, 5, 6, 0]])
    

    【讨论】:

      【解决方案2】:

      您可以使用 numpy.triu_indices 或 numpy.tril_indices:

      >>> a=np.array([[0, 0, 0, 0],
      ...             [1, 0, 0, 0],
      ...             [2, 3, 0, 0],
      ...             [4, 5, 6, 0]])
      >>> irows,icols = np.triu_indices(len(a),1)
      >>> a[irows,icols]=a[icols,irows]
      >>> a
      array([[0, 1, 2, 4],
             [1, 0, 3, 5],
             [2, 3, 0, 6],
             [4, 5, 6, 0]])
      

      【讨论】:

      • @DSM 我已经更正了我原来的答案,现在在我的数组中得到对称
      • 这是一个比 DSM 更好的答案,因为它不依赖于对角线元素为零。
      猜你喜欢
      • 1970-01-01
      • 2013-05-02
      • 2011-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-21
      • 2012-02-12
      • 2018-04-29
      相关资源
      最近更新 更多