From 2fedc274232bdf944dcc86eb05265852de7d1262 Mon Sep 17 00:00:00 2001 From: Simon Kornblith Date: Tue, 19 May 2015 19:10:02 -0400 Subject: [PATCH] Fix sparse matrix nits, fixes #9917, fixes #11032 --- base/sparse/sparsematrix.jl | 13 ++++++++++--- test/sparsedir/sparse.jl | 4 ++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/base/sparse/sparsematrix.jl b/base/sparse/sparsematrix.jl index 8cc9f676a3525..3c2a57844661b 100644 --- a/base/sparse/sparsematrix.jl +++ b/base/sparse/sparsematrix.jl @@ -184,7 +184,9 @@ convert{T}(::Type{AbstractMatrix{T}}, A::SparseMatrixCSC) = convert(SparseMatrix convert(::Type{Matrix}, S::SparseMatrixCSC) = full(S) function full{Tv}(S::SparseMatrixCSC{Tv}) - A = zeros(Tv, S.m, S.n) + # Handle cases where zero(Tv) is not defined but the array is dense. + # (Should we really worry about this?) + A = length(S) == nnz(S) ? Array(Tv, S.m, S.n) : zeros(Tv, S.m, S.n) for col = 1 : S.n, k = S.colptr[col] : (S.colptr[col+1]-1) A[S.rowval[k], col] = S.nzval[k] end @@ -1223,7 +1225,7 @@ function rangesearch(haystack::Range, needle) (rem==0 && 1<=i+1<=length(haystack)) ? i+1 : 0 end -getindex(A::SparseMatrixCSC, i::Integer) = getindex(A, ind2sub(size(A),i)) +getindex(A::SparseMatrixCSC, i::Integer) = isempty(A) ? throw(BoundsError()) : getindex(A, ind2sub(size(A),i)) getindex(A::SparseMatrixCSC, I::Tuple{Integer,Integer}) = getindex(A, I[1], I[2]) function getindex{T}(A::SparseMatrixCSC{T}, i0::Integer, i1::Integer) @@ -1636,7 +1638,11 @@ function getindex{Tv}(A::SparseMatrixCSC{Tv}, I::AbstractArray{Bool}) end function getindex{Tv}(A::SparseMatrixCSC{Tv}, I::AbstractArray) - szA = size(A); colptrA = A.colptr; rowvalA = A.rowval; nzvalA = A.nzval + szA = size(A) + nA = szA[1]*szA[2] + colptrA = A.colptr + rowvalA = A.rowval + nzvalA = A.nzval n = length(I) outm = size(I,1) @@ -1652,6 +1658,7 @@ function getindex{Tv}(A::SparseMatrixCSC{Tv}, I::AbstractArray) idxB = 1 for i in 1:n + ((I[i] < 1) | (I[i] > nA)) && throw(BoundsError()) row,col = ind2sub(szA, I[i]) for r in colptrA[col]:(colptrA[col+1]-1) @inbounds if rowvalA[r] == row diff --git a/test/sparsedir/sparse.jl b/test/sparsedir/sparse.jl index 0c2e3d1fb41e2..5eb02cf81e588 100644 --- a/test/sparsedir/sparse.jl +++ b/test/sparsedir/sparse.jl @@ -749,6 +749,10 @@ end # issue #9917 @test sparse([]') == reshape(sparse([]), 1, 0) +@test full(sparse([])) == zeros(0, 1) +@test_throws BoundsError sparse([])[1] +x = speye(100) +@test_throws BoundsError x[-10:10] for T in (Int, Float16, Float32, Float64, BigInt, BigFloat) let R=rand(T[1:100;],2,2), I=rand(T[1:100;],2,2)