CrabMan
CrabMan

Reputation: 1758

How to index array by one dimension only if I don't know the total number of dimensions?

I have a (possibly multidimensional) array X. It has at least k dimensions. I don't know how many dimensions it has. How do I index it by k-th dimension only?

E.g. if X is 4-dimensional, k is 3, and the desired index is 7, I want to get X[:, :, 7, :].

Upvotes: 3

Views: 192

Answers (2)

tholy
tholy

Reputation: 12179

In addition to Matt's excellent answer, let me add that in these cases it's often the case that one axis has particular "meaning." In such cases, it's worth considering a package like AxisArrays:

julia> using AxisArrays

julia> movie = AxisArray(rand(720, 1280, 50), :vertical, :horizontal, :time);

julia> timeslice = movie[Axis{:time}(5)];    # index along the time dimension

julia> size(timeslice)
(720, 1280)

This allows you to guarantee a meaningful outcome no matter how your data are stored. For example, the above code would take a time-slice even if movie were a 3d volume vs. time (e.g., MRI scan) rather than a 2d picture vs. time.

Upvotes: 3

mbauman
mbauman

Reputation: 31362

Use selectdim:

julia> X = reshape(1:2*3*5*7, 5, 3, 7, 2);

julia> selectdim(X, 3, 7)
5×3×2 view(reshape(::UnitRange{Int64}, 5, 3, 7, 2), :, :, 7, :) with eltype Int64:
[:, :, 1] =
 91   96  101
 92   97  102
 93   98  103
 94   99  104
 95  100  105

[:, :, 2] =
 196  201  206
 197  202  207
 198  203  208
 199  204  209
 200  205  210

julia> selectdim(X, 3, 7) == X[:, :, 7, :]
true

Upvotes: 5

Related Questions