Extract upper or lower triangular part of a numpy matrix

后端 未结 3 1759
野的像风
野的像风 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 07:50

    To extract the upper triangle values to a flat vector, you can do something like the following:

    import numpy as np
    
    a = np.array([[1,2,3],[4,5,6],[7,8,9]])
    print(a)
    
    #array([[1, 2, 3],
    #       [4, 5, 6],
    #       [7, 8, 9]])
    
    a[np.triu_indices(3)]
    #or
    list(a[np.triu_indices(3)])
    
    #array([1, 2, 3, 5, 6, 9])
    

    Similarly, for the lower triangle, use np.tril.


    IMPORTANT

    If you want to extract the values that are above the diagonal (or below) then use the k argument. This is usually used when the matrix is symmetric.

    import numpy as np
    
    a = np.array([[1,2,3],[4,5,6],[7,8,9]])
    
    #array([[1, 2, 3],
    #       [4, 5, 6],
    #       [7, 8, 9]])
    
    a[np.triu_indices(3, k = 1)]
    
    # this returns the following
    array([2, 3, 6])
    

    EDIT (11.11.2019):

    To put back the extracted vector into a 2D symmetric array, one can follow my answer here: https://stackoverflow.com/a/58806626/5025009

提交回复
热议问题