diff --git a/README.md b/README.md index 7def7efee..4b60fff22 100644 --- a/README.md +++ b/README.md @@ -291,6 +291,7 @@ Currently, the `@compat` macro supports the following syntaxes: `Compat.median`, `Compat.minimum`, `Compat.prod`, `Compat.reduce`, `Compat.sort`, `Compat.std`, `Compat.sum`, `Compat.var`, and `Compat.varm` with `dims` keyword argument ([#25989],[#26369]). +* `selectdim` to obtain a view of an array with a specified index for a specified dimension ([#26009]). ## Renaming @@ -607,6 +608,7 @@ includes this fix. Find the minimum version from there. [#25989]: https://github.com/JuliaLang/julia/issues/25989 [#25990]: https://github.com/JuliaLang/julia/issues/25990 [#25998]: https://github.com/JuliaLang/julia/issues/25998 +[#26009]: https://github.com/JuliaLang/julia/issues/26009 [#26069]: https://github.com/JuliaLang/julia/issues/26069 [#26089]: https://github.com/JuliaLang/julia/issues/26089 [#26149]: https://github.com/JuliaLang/julia/issues/26149 diff --git a/src/Compat.jl b/src/Compat.jl index f1835344f..c60daaed2 100644 --- a/src/Compat.jl +++ b/src/Compat.jl @@ -1778,6 +1778,17 @@ if VERSION < v"0.7.0-DEV.4534" dims===nothing ? Base.reverse(a) : Base.flipdim(a, dims) end +if !isdefined(Base, :selectdim) # 0.7.0-DEV.3976 + export selectdim + @inline selectdim(A::AbstractArray, d::Integer, i) = _selectdim(A, d, i, Base.setindex(axes(A), i, d)) + @noinline function _selectdim(A, d, i, idxs) + d >= 1 || throw(ArgumentError("dimension must be ≥ 1")) + nd = ndims(A) + d > nd && (i == 1 || throw(BoundsError(A, (ntuple(k->Colon(),d-1)..., i)))) + return view(A, idxs...) + end +end + include("deprecated.jl") end # module Compat diff --git a/test/runtests.jl b/test/runtests.jl index fe5e3c898..cb365e650 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -1673,4 +1673,14 @@ end @test length(Compat.CartesianIndices((1:2,))) == 2 @test length(Compat.CartesianIndices((1:2, -1:1))) == 6 +# 0.7.0-DEV.3976 +let A = rand(5,5) + @test selectdim(A, 1, 3) == A[3, :] + @test selectdim(A, 1, 1:3) == A[1:3, :] + @test selectdim(A, 2, 3) == A[:, 3] + @test selectdim(A, 2, 1:3) == A[:, 1:3] + selectdim(A, 1, 3)[3] = 42 + @test A[3,3] == 42 +end + nothing