SparseArrays.jl
SparseArrays.jl copied to clipboard
Error with SparseArrays broadcast operation
I have a function that is broadcasting a multiplication between a vector and a vector of vectors. This works as expected on dense vectors. If I pass a sparse vector as first argument, I get an unexpected error.
Minimum example to reproduce:
using SparseArrays
x = [1,0]
xs = sparse(x)
y = [[1, 2], [3, 4]]
julia> x .* y
2-element Vector{Vector{Int64}}:
[1, 2]
[0, 0]
julia> xs .* y
ERROR: MethodError: no method matching zero(::Type{Vector{Int64}})
this is not unexpected IMO: operations that need access to non-stored zero values (e.g. linear operations or broadcast) on a sparse array can only be reasonably implemented for value types Tv for which zero(::Type{Tv}) is defined. Vector is not one of them. You can use StaticArrays or define your own type for this.
I understand why zero(::Type{Tv}) is needed for the variable xs (which is sparse), but I'm missing why it is being evaluated for y. If y were sparse and xs were not, I would understand the error and fully agree with your comment.
You're right. Digging a bit, the problem seems to be that arrays are first converted to sparse in broadcast (_sparsifystructured in SparseArrays/src/higherorderfns.jl)
However, note that the result is a SparseVector{Vector{Int}}, so in principle zero could still be needed (e.g. to show the matrix on some displays). So I'm still not sure if this is a bug...