Skip to content

Commit

Permalink
Allow indexing of SparseMatrixCSC by array of CartesianIndex (#33225
Browse files Browse the repository at this point in the history
)
  • Loading branch information
goggle authored and timholy committed Sep 14, 2019
1 parent 04234fb commit 77fa781
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
2 changes: 2 additions & 0 deletions base/multidimensional.jl
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,8 @@ module IteratorsMD
return I
end

Base._ind2sub(t::Tuple, ind::CartesianIndex) = Tuple(ind)

# Iteration over the elements of CartesianIndex cannot be supported until its length can be inferred,
# see #23719
Base.iterate(::CartesianIndex) =
Expand Down
2 changes: 1 addition & 1 deletion stdlib/SparseArrays/src/sparsevector.jl
Original file line number Diff line number Diff line change
Expand Up @@ -663,6 +663,7 @@ end

function getindex(A::AbstractSparseMatrixCSC{Tv,Ti}, I::AbstractVector) where {Tv,Ti}
require_one_based_indexing(A, I)
@boundscheck checkbounds(A, I)
szA = size(A)
nA = szA[1]*szA[2]
colptrA = getcolptr(A)
Expand All @@ -676,7 +677,6 @@ function getindex(A::AbstractSparseMatrixCSC{Tv,Ti}, I::AbstractVector) where {T

idxB = 1
for i in 1:n
((I[i] < 1) | (I[i] > nA)) && throw(BoundsError(A, I))
row,col = Base._ind2sub(szA, I[i])
for r in colptrA[col]:(colptrA[col+1]-1)
@inbounds if rowvalA[r] == row
Expand Down
15 changes: 15 additions & 0 deletions stdlib/SparseArrays/test/sparse.jl
Original file line number Diff line number Diff line change
Expand Up @@ -870,6 +870,21 @@ end
end
end

# indexing by array of CartesianIndex (issue #30981)
S = sprand(10, 10, 0.4)
inds_sparse = S[findall(S .> 0.2)]
M = Matrix(S)
inds_dense = M[findall(M .> 0.2)]
@test Array(inds_sparse) == inds_dense
inds_out = Array([CartesianIndex(1, 1), CartesianIndex(0, 1)])
@test_throws BoundsError S[inds_out]
pop!(inds_out); push!(inds_out, CartesianIndex(1, 0))
@test_throws BoundsError S[inds_out]
pop!(inds_out); push!(inds_out, CartesianIndex(11, 1))
@test_throws BoundsError S[inds_out]
pop!(inds_out); push!(inds_out, CartesianIndex(1, 11))
@test_throws BoundsError S[inds_out]

# workaround issue #7197: comment out let-block
#let S = SparseMatrixCSC(3, 3, UInt8[1,1,1,1], UInt8[], Int64[])
S1290 = SparseMatrixCSC(3, 3, UInt8[1,1,1,1], UInt8[], Int64[])
Expand Down

0 comments on commit 77fa781

Please sign in to comment.