Skip to content

Instantly share code, notes, and snippets.

@mauro3

mauro3/with.jl Secret

Created March 13, 2018 14:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mauro3/b45c293d88167cd6cee622d08c05b5c0 to your computer and use it in GitHub Desktop.
Save mauro3/b45c293d88167cd6cee622d08c05b5c0 to your computer and use it in GitHub Desktop.
sparse setindex! with !
function setindex!(A!::SparseMatrixCSC{Tv,Ti}, v::Tv, i::Ti, j::Ti) where Tv where Ti<:Integer
if !((1 <= i <= A!.m) & (1 <= j <= A!.n))
throw(BoundsError(A!, (i,j)))
end
coljfirstk = Int(A!.colptr[j])
coljlastk = Int(A!.colptr[j+1] - 1)
searchk = searchsortedfirst(A!.rowval, i, coljfirstk, coljlastk, Base.Order.Forward)
if searchk <= coljlastk && A!.rowval[searchk] == i
# Column j contains entry A![i,j]. Update and return
A!.nzval[searchk] = v
return A!
end
# Column j does not contain entry A![i,j]. If v is nonzero, insert entry A![i,j] = v
# and return. If to the contrary v is zero, then simply return.
if v != 0
insert!(A!.rowval, searchk, i)
insert!(A!.nzval, searchk, v)
@simd for m in (j + 1):(A!.n + 1)
@inbounds A!.colptr[m] += 1
end
end
return A!
end
function setindex!(A::SparseMatrixCSC{Tv,Ti}, v::Tv, i::Ti, j::Ti) where Tv where Ti<:Integer
if !((1 <= i <= A.m) & (1 <= j <= A.n))
throw(BoundsError(A, (i,j)))
end
coljfirstk = Int(A.colptr[j])
coljlastk = Int(A.colptr[j+1] - 1)
searchk = searchsortedfirst(A.rowval, i, coljfirstk, coljlastk, Base.Order.Forward)
if searchk <= coljlastk && A.rowval[searchk] == i
# Column j contains entry A[i,j]. Update and return
A.nzval[searchk] = v
return A
end
# Column j does not contain entry A[i,j]. If v is nonzero, insert entry A[i,j] = v
# and return. If to the contrary v is zero, then simply return.
if v != 0
insert!(A.rowval, searchk, i)
insert!(A.nzval, searchk, v)
@simd for m in (j + 1):(A.n + 1)
@inbounds A.colptr[m] += 1
end
end
return A
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment