As noted in the docs for LUDecomposition[]
, the two triangles are by default returned together as a single array; this is customary for LU decomposition routines, as in the original LINPACK and MATLAB's lu()
. In fact, exactly this same format is stored internally by the LinearSolveFunction[]
returned by LinearSolve[]
:
a = {{1, 2, 3}, {2, 4, 1}, {2, 5, 7}};
{lu, piv, cond} = LUDecomposition[{{1, 2, 3}, {2, 4, 1}, {2, 5, 7}}]
{{{1, 2, 3}, {2, 1, 1}, {2, 0, -5}}, {1, 3, 2}, 1}
ls = LinearSolve[{{1, 2, 3}, {2, 4, 1}, {2, 5, 7}}];
ls[[2, 3]]
{{{1, 2, 3}, {2, 1, 1}, {2, 0, -5}}, {1, 3, 2}, 1}
You will need the first two results to reconstitute your original matrix. (The third result is a valuable diagnostic quantity called the matrix condition number; I should hope that this will eventually be introduced to you in your classes.)
In MATLAB, one could use the utility functions tril()
and triu()
to extract the triangular factors from the compressed array representing the LU decomposition. In Mathematica, on the other hand, belisarius has shown the way it used to be done. However, since version 7, Mathematica has been able to catch up to MATLAB in this regard, since the functions LowerTriangularize[]
and UpperTriangularize[]
became built-in:
l = LowerTriangularize[lu, -1] + IdentityMatrix[Length[lu]]
{{1, 0, 0}, {2, 1, 0}, {2, 0, 1}}
u = UpperTriangularize[lu]
{{1, 2, 3}, {0, 1, 1}, {0, 0, -5}}
To reconstitute the permutation matrix, do this:
p = IdentityMatrix[Length[lu]][[piv]]
{{1, 0, 0}, {0, 0, 1}, {0, 1, 0}}
Now, we can easily check the decomposition:
p.a - l.u
{{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}
As an aside, here is how one computes Det[a]
using the results of LUDecomposition[a]
:
{Signature[piv] Tr[lu, Times], Det[a]}
{5, 5}