diff --git a/src/oneelement.jl b/src/oneelement.jl index f6204abb..c72bcd2d 100644 --- a/src/oneelement.jl +++ b/src/oneelement.jl @@ -372,6 +372,16 @@ function broadcasted(::DefaultArrayStyle{N}, ::typeof(\), x::Number, r::OneEleme OneElement(x \ r.val, r.ind, axes(r)) end +# reshape + +function Base.reshape(A::OneElement, shape::Tuple{Vararg{Int}}) + prod(shape) == length(A) || throw(DimensionMismatch("new dimension $shape must be consistent with array size $(length(A))")) + # we use the fact that the linear index of the non-zero value is preserved + oldlinind = LinearIndices(A)[A.ind...] + newcartind = CartesianIndices(shape)[oldlinind] + OneElement(A.val, Tuple(newcartind), shape) +end + # show _maybesize(t::Tuple{Base.OneTo{Int}, Vararg{Base.OneTo{Int}}}) = size.(t,1) _maybesize(t) = t diff --git a/test/runtests.jl b/test/runtests.jl index 2e2aba22..d4b2bb95 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -2215,6 +2215,18 @@ end @test adjoint(A) == OneElement(3, (1,2), (1,4)) end + @testset "reshape" begin + for O in (OneElement(2, (2,3), (4,5)), OneElement(2, (2,), (20,)), + OneElement(2, (1,2,2), (2,2,5))) + A = Array(O) + for shp in ((2,5,2), (5,1,4), (20,), (2,2,5,1,1)) + @test reshape(O, shp) == reshape(A, shp) + end + end + O = OneElement(2, (), ()) + @test reshape(O, ()) === O + end + @testset "isassigned" begin f = OneElement(2, (3,3), (4,4)) @test !isassigned(f, 0, 0)