Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Modify sparse identity matrix in julia sparse

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading