Modify sparse identity matrix in julia sparse

Viewed 100

I'm creating an identity sparse matrix because I would like to modify some entries of this matrix:

Is = copy(sparse(I, N^2, N^2))

However, I got the error (e.g. for Is[1,3] = -1)

ERROR: LoadError: InexactError: Bool(-1.0)

Is there a way I can modify Is? I don't want to run two loops of size N because this parameter is very big.

1 Answers

Example:

julia> using SparseArrays, LinearAlgebra

julia> Is = copy(sparse(I, N^2, N^2));

julia> Is[3, 5] = -1.0;
ERROR: InexactError: Bool(-1.0)
Stacktrace:
 [1] Bool
   @ ./float.jl:158 [inlined]
 [2] convert
   @ ./number.jl:7 [inlined]
 [3] _setindex_scalar!(A::SparseMatrixCSC{Bool, Int64}, _v::Float64, _i::Int64, _j::Int64)
   @ SparseArrays ~/Desktop/Julia/Julia-1.8.app/Contents/Resources/julia/share/julia/stdlib/v1.8/SparseArrays/src/sparsematrix.jl:2670
 [4] setindex!(A::SparseMatrixCSC{Bool, Int64}, _v::Float64, _i::Int64, _j::Int64)
   @ SparseArrays ~/Desktop/Julia/Julia-1.8.app/Contents/Resources/julia/share/julia/stdlib/v1.8/SparseArrays/src/sparsematrix.jl:2667
 [5] top-level scope
   @ REPL[11]:1

Looks like Is is expected to contain booleans, so Julia attempts to convert -1.0 to a Boolean and fails. Indeed, Is contains booleans:

julia> typeof(Is)
SparseMatrixCSC{Bool, Int64}

Why is that? Apparently, I is UniformScaling{Bool}, so I is an identity matrix of booleans. You can multiply it by 1.0 to get floats:

julia> 1.0*I
UniformScaling{Float64}
1.0*I

Then create the new matrix:

julia> Is = copy(sparse(1.0*I, N^2, N^2));

julia> eltype(Is)
Float64

julia> Is[3,5] = -1.0;
Related