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:

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?

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.