Julia 中多维数组的子维数组

Subdimensional array from multidimensional array in Julia

使用 NumPy,我可以在不知道原始数组维度的情况下访问 subdimensional array from a multidimensional array

import numpy as np
a = np.zeros((2, 3, 4))  # A 2-by-3-by-4 array of zeros
a[0]  # A 3-by-4 array of zeros

但是对于 Julia,我不知所措。看来我必须知道a的维度才能做到这一点:

a = zeros(2, 3, 4)  # A 2-by-3-by-4 array of zeros
a[1, :, :]  # A 3-by-4 array of zeros

如果我不知道a的维度怎么办?

selectdim 给出了您正在寻找的视图,

a = zeros(2, 3, 4)
selectdim(a,1,1)

如果想按顺序遍历每个“次维数组”,也可以使用eachslice:

julia> a = reshape(1:24, (2, 3, 4));

julia> eachslice(a, dims = 1) |> first
3×4 view(reshape(::UnitRange{Int64}, 2, 3, 4), 1, :, :) with eltype Int64:
 1   7  13  19
 3   9  15  21
 5  11  17  23

julia> for a2dims in eachslice(a, dims = 1)
         @show size(a2dims)
       end
size(a2dims) = (3, 4)
size(a2dims) = (3, 4)