Skip to content

Commit

Permalink
Merge pull request #11408 from JuliaLang/sjk/sparse-fixes
Browse files Browse the repository at this point in the history
Fix sparse matrix nits, and make sparse matrix construction fail if zero(Tv) not defined
  • Loading branch information
simonster committed May 30, 2015
2 parents 7d8178c + 2fedc27 commit d8ca7a2
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
13 changes: 10 additions & 3 deletions base/sparse/sparsematrix.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down
4 changes: 4 additions & 0 deletions test/sparsedir/sparse.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit d8ca7a2

Please sign in to comment.