FillArrays.jl icon indicating copy to clipboard operation
FillArrays.jl copied to clipboard

Operations with Eye do not preserve sparsity

Open amilsted opened this issue 1 year ago • 6 comments

Hi, I've noticed that SquareEye, since it is a LinearAlgebra.Diagonal preserves sparsity in many operations. For example:

julia> using FillArrays

julia> using SparseArrays

julia> E = Eye(2)
2×2 Eye{Float64}

julia> M = sprand(2,2, 0.5)
2×2 SparseMatrixCSC{Float64, Int64} with 3 stored entries:
 0.906128   0.408236
 0.0285949   ⋅ 

julia> E + M
2×2 SparseMatrixCSC{Float64, Int64} with 4 stored entries:
 1.90613    0.408236
 0.0285949  1.0

julia> kron(E, E)  # although it would be nice is this were another SquareEye!
4×4 Diagonal{Float64, Vector{Float64}}:
 1.0   ⋅    ⋅    ⋅ 
  ⋅   1.0   ⋅    ⋅ 
  ⋅    ⋅   1.0   ⋅ 
  ⋅    ⋅    ⋅   1.0

However, general Eye typically converts to a dense matrix:

julia> E = Eye(2,2)
2×2 Eye{Float64}

julia> E + M
2×2 Matrix{Float64}:
 1.90613    0.408236
 0.0285949  1.0

julia> kron(E,E)
4×4 Matrix{Float64}:
 1.0  0.0  0.0  0.0
 0.0  1.0  0.0  0.0
 0.0  0.0  1.0  0.0
 0.0  0.0  0.0  1.0

This was quite surprising to me. Could we add some operator overloads to keep things sparse in the Eye case?

amilsted avatar Jun 22 '23 17:06 amilsted