tags:

views:

42

answers:

2

for example, there is a matrix:

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

It's a LU Decomposition (Doolittle’s decomposition) result.(A = [L\U])
I want to get L and U from A.
U should be:

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

L should be:

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

then, want I want to know is how to get the L and U from A?

+2  A: 

You don't need any index manipulation. Just use tril, triu and identity functions:

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. ]]
DzinX
@Dzinx, works like a charm, thanks.
sunqiang
+1  A: 

What you want doesn't look like LU-decomposition to me, 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 decomposition is available in 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. ]])
@user333700, thanks for the very clear lecture. sorry for my broken English. In fact, A is already the result of a LU Decomposition (Doolittle’s decomposition), I got A as a return value from another LU Decomposition function(not scipy.linalg.lu). It save L and U as the form [L\U](aka, A). np.dpt(L, U) will output the original Matrix(just the same as your's np.dot(L_, U_)).
sunqiang
I guess I didn't read the part that it is the LU result carefully enough. Sorry
@user333700, glad to meet you, and thanks for the help. :)
sunqiang