Extract upper or lower triangular part of a numpy matrix

后端 未结 3 1758
野的像风
野的像风 2020-11-28 07:22

I have a matrix A and I want 2 matrices U and L such that U contains the upper triangular elements of A (all elements abo

3条回答
  •  鱼传尺愫
    2020-11-28 08:05

    Use the Array Creation Routines of numpy.triu and numpy.tril to return a copy of a matrix with the elements above or below the k-th diagonal zeroed.

        >>> a = np.array([[1,2,3],[4,5,6],[7,8,9]])
        >>> a
        array([[1, 2, 3],
               [4, 5, 6],
               [7, 8, 9]])
    
        >>> tri_upper_diag = np.triu(a, k=0)
        >>> tri_upper_diag
        array([[1, 2, 3],
               [0, 5, 6],
               [0, 0, 9]])
    
        >>> tri_upper_no_diag = np.triu(a, k=1)
        >>> tri_upper_no_diag
        array([[0, 2, 3],
               [0, 0, 6],
               [0, 0, 0]])
    
        >>> tri_lower_diag = np.tril(a, k=0)
        >>> tri_lower_diag
        array([[1, 0, 0],
               [4, 5, 0],
               [7, 8, 9]])
    
        >>> tri_lower_no_diag = np.tril(a, k=-1)
        >>> tri_lower_no_diag
        array([[0, 0, 0],
               [4, 0, 0],
               [7, 8, 0]])
    

提交回复
热议问题