Skip to content

Commit

Permalink
Fix reshape for OneElement when indices lie outside axes (#378)
Browse files Browse the repository at this point in the history
  • Loading branch information
jishnub authored Aug 27, 2024
1 parent f72e220 commit 554ddf4
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/oneelement.jl
Original file line number Diff line number Diff line change
Expand Up @@ -419,9 +419,14 @@ end

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]
if all(in.(A.ind, axes(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]
else
# arbitrarily set to some value outside the domain
newcartind = shape .+ 1
end
OneElement(A.val, Tuple(newcartind), shape)
end

Expand Down
4 changes: 4 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2328,6 +2328,10 @@ end
end
O = OneElement(2, (), ())
@test reshape(O, ()) === O

O = OneElement(5, 3)
@test reshape(O, 1, 3) == reshape(Array(O), 1, 3)
@test reshape(reshape(O, 1, 3), 3) == O
end

@testset "isassigned" begin
Expand Down

0 comments on commit 554ddf4

Please sign in to comment.