Search code examples
matrixjuliasparse-matrix

How to convert sparse matrix to dense matrix in Julia


How do you convert a sparse matrix to a dense matrix in Julia? According to this I should be able to use full or Matrix, however full is evidently not standard in the SparseArrays module, and when I try to use Matrix:

    I = []
    J = []
    A = []

    for i in 1:3
        push!(I, i)
        push!(J, i^2)
        push!(A, sqrt(i))
    end

    sarr = sparse(I, J, A, 10, 10)
    arr = Matrix(sarr)

I get this error:

Exception has occurred: MethodError
MethodError: no method matching zero(::Type{Any})

Solution

  • It is enough to do collect(sarr) or Matrix(sarr).

    Note, however that your code uses untyped containers which is not recommended. Indexes in arrays are Ints so it should be:

    I = Int[]
    J = Int[]
    A = Float64[]
    
    for i in 1:3
        push!(I, i)
        push!(J, i^2)
        push!(A, sqrt(i))
    end
    
    sarr = sparse(I, J, A, 10, 10)
    

    Now you can do:

    julia> collect(sarr)
    10×10 Matrix{Float64}:
     1.0  0.0  0.0  0.0      0.0  0.0  0.0  0.0  0.0      0.0
     0.0  0.0  0.0  1.41421  0.0  0.0  0.0  0.0  0.0      0.0
     0.0  0.0  0.0  0.0      0.0  0.0  0.0  0.0  1.73205  0.0
     0.0  0.0  0.0  0.0      0.0  0.0  0.0  0.0  0.0      0.0
     0.0  0.0  0.0  0.0      0.0  0.0  0.0  0.0  0.0      0.0
     0.0  0.0  0.0  0.0      0.0  0.0  0.0  0.0  0.0      0.0
     0.0  0.0  0.0  0.0      0.0  0.0  0.0  0.0  0.0      0.0
     0.0  0.0  0.0  0.0      0.0  0.0  0.0  0.0  0.0      0.0
     0.0  0.0  0.0  0.0      0.0  0.0  0.0  0.0  0.0      0.0
     0.0  0.0  0.0  0.0      0.0  0.0  0.0  0.0  0.0      0.0