# LU factorisation of dense and sparse matrix

**URL:** https://discourse.julialang.org/t/lu-factorisation-of-dense-and-sparse-matrix/95393
**Category:** General Usage
**Tags:** question, linearalgebra
**Created:** [March 1, 2023, 3:23pm UTC](https://discourse.julialang.org/t/lu-factorisation-of-dense-and-sparse-matrix/95393 "2023-03-01T15:23:56Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![cvikas](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/cvikas/32/38874_2.png) [@cvikas](https://discourse.julialang.org/u/cvikas)
#### Post date: [March 1, 2023, 3:23pm UTC](https://discourse.julialang.org/t/lu-factorisation-of-dense-and-sparse-matrix/95393/1 "2023-03-01T15:23:56Z")

</div>

Hi guys,

I’ve been trying convert MATLAB code to Julia, and I observed LU factorization for sparse and dense matrix of the same matrix give different number of non-zero fill-ins.

Consider the following example:

```julia
using LinearAlgebra
using SparseArrays
using Test

#LU factorisation of sparse matrix
A_sparse = sprand(Float64, 10, 10, 0.3)
F = lu(A_sparse)
sL, sU = F.L, F.U

#LU factorisation of dense matrix
L, U = lu(Matrix(A_sparse))

#Testing
nnz(sL) .== nnz(sparse(L))
nnz(sU) .== nnz(sparse(U))

@test Matrix(sL) ≈ L atol=1e-5
@test Matrix(sU) ≈ U atol=1e-5

```

All tests fail for me. Any ideas why this might be?

---

<div class="post-metadata">

### Author: ![Per](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/per/32/10387_2.png) [@Per](https://discourse.julialang.org/u/Per)
#### Post date: [March 1, 2023, 3:39pm UTC](https://discourse.julialang.org/t/lu-factorisation-of-dense-and-sparse-matrix/95393/2 "2023-03-01T15:39:41Z")

</div>

My guess would be that sparse/dense routines use different permutations, where the sparse version tries to minimise fill-in while the dense prioritises numeric stability.

---

<div class="post-metadata">

### Author: ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)
#### Post date: [March 1, 2023, 5:06pm UTC](https://discourse.julialang.org/t/lu-factorisation-of-dense-and-sparse-matrix/95393/3 "2023-03-01T17:06:54Z")

</div>

Definitely. The main trick of sparse LU is to find a fill-reducing permutation (such as [minimum degree](https://en.wikipedia.org/wiki/Minimum_degree_algorithm)).

However, it’s possible to specify a custom permutation to the sparse-LU routine ([`lu` support for custom permutation (like in `cholesky`) · Issue #116 · JuliaSparse/SparseArrays.jl · GitHub](https://github.com/JuliaSparse/SparseArrays.jl/issues/116)), so in principle you should be able to force it to use the same permutation as the dense LU routine to get them to produce the same fill-in. Not sure why this would be worth the trouble, however.
