Skip to content

view fails when new axis is prepended and last axis is selected #53209

@vadim-z

Description

@vadim-z

Hello,

In 1.10.0 view fails when:

  1. new axis is prepended with [CartesianIndex()]
  2. the last axis is chosen at some value
julia> A = rand(2,3)
2×3 Matrix{Float64}:
 0.562201  0.212601  0.193508
 0.408022  0.978427  0.823557

julia> A[[CartesianIndex()], :, 1]
1×2 Matrix{Float64}:
 0.562201  0.408022

julia> view(A, [CartesianIndex()], :, 1)
ERROR: ArgumentError: number of indices (1) must match the parent dimensionality (2)
Stacktrace:
 [1] check_parent_index_match(parent::Matrix{Float64}, #unused#::Tuple{Bool})
   @ Base .\subarray.jl:43
 [2] check_parent_index_match(parent::Matrix{Float64}, indices::Tuple{Vector{CartesianIndex{0}}, Base.Slice{Base.OneTo{Int64}}})
   @ Base .\subarray.jl:41
 [3] SubArray
   @ .\subarray.jl:21 [inlined]
 [4] SubArray
   @ .\subarray.jl:32 [inlined]
 [5] SubArray
   @ .\subarray.jl:28 [inlined]
 [6] unsafe_view
   @ .\subarray.jl:219 [inlined]
 [7] view(::Matrix{Float64}, ::Vector{CartesianIndex{0}}, ::Function, ::Int64)
   @ Base .\subarray.jl:180
 [8] top-level scope
   @ REPL[11]:1

This shouldn't happen according to the second block of example.

Analysis of code brought the following lines:

julia/base/subarray.jl

Lines 207 to 210 in 94fd312

if length(J) > ndims(A) && J[N+1:end] isa Tuple{Vararg{Int}}
# view([1,2,3], :, 1) does not need to reshape
return unsafe_view(A, J[1:N]...)
end

As we see, the condition holds because the length of J is 3 and ndims(A) is 2 and the last index is integer. Therefore view proceeds to the line 209.

However, because of [CartesianIndex()], the array really needs to be reshaped.

When I explicitly type line 211, it works as expected:

julia> A = rand(2,3)
2×3 Matrix{Float64}:
 0.784263  0.958573   0.869377
 0.619148  0.0324357  0.966875

julia> J = map(i->Base.unalias(A,i), to_indices(A, ([CartesianIndex()], :, 1)))
([CartesianIndex()], Base.Slice(Base.OneTo(2)), 1)

julia> Base.unsafe_view(Base._maybe_reshape_parent(A, Base.index_ndims(J...)), J...)
1×2 view(::Matrix{Float64}, [CartesianIndex()], :, 1) with eltype Float64:
 0.784263  0.619148

With best regards, Vadim Zborovskii

Metadata

Metadata

Assignees

No one assigned

    Labels

    arrays[a, r, r, a, y, s]bugIndicates an unexpected problem or unintended behavior

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions