如何找到下三角形numpy矩阵的方阵? (旋转的上三角形)[重复]

时间:2022-03-01 12:50:29

This question already has an answer here:

这个问题在这里已有答案:

I generated a lower triangular matrix, and I want to complete the matrix using the values in the lower triangular matrix to form a square matrix.

我生成了一个下三角矩阵,我想用下三角矩阵中的值完成矩阵,形成一个方阵。

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

I want to generate the following complete matrix, maintaining the zero diagonal:

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

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

Thanks.

2 个解决方案

#1


2  

How about:

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

See also fliplr(m)[::-1], etc.

另见fliplr(m)[:: - 1]等。

#2


0  

without any addition:

没有任何补充:

>>> 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]])

#1


2  

How about:

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

See also fliplr(m)[::-1], etc.

另见fliplr(m)[:: - 1]等。

#2


0  

without any addition:

没有任何补充:

>>> 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]])