# LUDecomposition does not give the expected results

I'm having trouble using `LUDecomposition` with pivoting. I read the Mathematica help on this particular command, but I'm still lost. Take a matrix like:

````a = {{1, 2, 3}, {2, 4, 1}, {2, 5, 7}} `
```

I evaluated

````{lu, p, c} = LUDecomposition[{{1, 2, 3}, {2, 4, 1}, {2, 5, 7}}] `
```

and got

````{{{1, 2, 3}, {2, 1, 1}, {2, 0, -5}}, {1, 3, 2}, 0} `
```

I don't really understand how to interpret this result, assuming that it's correct.

Replay

``````m = {{1, 2, 3}, {2, 4, 1}, {2, 5, 7}};
{lu, p, c} = LUDecomposition[m];
l = lu SparseArray[{i_, j_} /; j < i -> 1, {3, 3}] + IdentityMatrix;
u = lu SparseArray[{i_, j_} /; j >= i -> 1, {3, 3}];
l.u == m[[p]]
(* True *)
```
```

l.u is equal to a permutation of the rows of m

``````MatrixForm /@ {l, u}
```
```

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}
```
```
Category: matrix Time: 2015-08-01 Views: 0

## Related post

### server

Copyright (C) avrocks.com, All Rights Reserved.

processed in 0.199 (s). 12 q(s)