代码之家  ›  专栏  ›  技术社区  ›  sunqiang

数据数组的索引问题

  •  1
  • sunqiang  · 技术社区  · 14 年前

    例如,有一个矩阵:

    import numpy as np
    A = np.array([[ 8. , -6. , 2. ], 
                  [-0.5, 8. , -6. ], 
                  [ 0.5, -0.5, 2. ]])
    

    这是一个LU分解(doolitt_s分解)结果。
    我想从A那里得到L和U。
    U应该是:

    U = np.array([[ 8., -6., 2.], 
                  [ 0., 8., -6.], 
                  [ 0., 0.,  2.]])
    

    L应该是:

    L = np.array([[ 1. , 0. , 0. ], 
                  [-0.5, 1. , 0. ], 
                  [ 0.5, -0.5, 1.]])
    

    那么,我想知道的是如何从A中得到L和U?

    2 回复  |  直到 14 年前
        1
  •  2
  •   Dzinx    14 年前

    您不需要任何索引操作。只使用 tril , triu identity 功能:

    import numpy as np
    A = np.array([[ 8. , -6. , 2. ], 
                  [-0.5, 8. , -6. ], 
                  [ 0.5, -0.5, 2. ]])
    
    U = np.triu(A)
    
    #[[ 8. -6.  2.]
    # [-0.  8. -6.]
    # [ 0. -0.  2.]]
    
    L = np.tril(A, k=-1) + np.identity(3)
    
    #[[ 1.   0.   0. ]
    # [-0.5  1.   0. ]
    # [ 0.5 -0.5  1. ]]
    
        2
  •  1
  •   Josef    14 年前

    你想要的在我看来不像是卢分解, http://en.wikipedia.org/wiki/LU_decomposition

    >>> U_ = np.array([[ 8., -6., 2.],
                  [ 0., 8., -6.],
                  [ 0., 0.,  2.]])
    >>> L_ = np.array([[ 1. , 0. , 0. ],
                  [-0.5, 1. , 0. ],
                  [ 0.5, -0.5, 1.]])
    >>> np.dot(L_, U_)
    array([[  8.,  -6.,   2.],
           [ -4.,  11.,  -7.],
           [  4.,  -7.,   6.]])
    

    lu分解在scipy.linalg中可用

    >>> A = np.array([[ 8. , -6. , 2. ], [-0.5, 8. , -6. ], [ 0.5, -0.5, 2. ]])
    >>> import scipy.linalg as spla
    >>> P, L, U = spla.lu(A)
    >>> L
    array([[ 1.        ,  0.        ,  0.        ],
           [-0.0625    ,  1.        ,  0.        ],
           [ 0.0625    , -0.01639344,  1.        ]])
    >>> U
    array([[ 8.        , -6.        ,  2.        ],
           [ 0.        ,  7.625     , -5.875     ],
           [ 0.        ,  0.        ,  1.77868852]])
    >>> np.dot(L, U)
    array([[ 8. , -6. ,  2. ],
           [-0.5,  8. , -6. ],
           [ 0.5, -0.5,  2. ]])