5

I am using Julia1.6

Here, X is a D-order multidimeonal array. How can I slice from i to j on the d-th axis of X ?

Here is an exapmle in case of D=6 and d=4.

X = rand(3,5,6,6,5,6)
Y = X[:,:,:,i:j,:,:]

i and j are given values which are smaller than 6 in the above example.

Sakurai.JJ
  • 553
  • 3
  • 10

3 Answers3

4

If you need to just slice on a single axis, use the built in selectdim(A, dim, index), e.g., selectdim(X, 4, i:j).

If you need to slice more than one axis at a time, you can build the array that indexes the array by first creating an array of all Colons and then filling in the specified dimensions with the specified indices.

function selectdims(A, dims, indices)
   indexer = repeat(Any[:], ndims(A))
   for (dim, index) in zip(dims, indices)
       indexer[dim] = index
   end
   return A[indexer...]
end
BallpointBen
  • 9,406
  • 1
  • 32
  • 62
3

You can use the built-in function selectdim

help?> selectdim
search: selectdim

  selectdim(A, d::Integer, i)

  Return a view of all the data of A where the index for dimension d equals i.

  Equivalent to view(A,:,:,...,i,:,:,...) where i is in position d.

  Examples
  ≡≡≡≡≡≡≡≡≡≡

  julia> A = [1 2 3 4; 5 6 7 8]
  2×4 Matrix{Int64}:
   1  2  3  4
   5  6  7  8

  julia> selectdim(A, 2, 3)
  2-element view(::Matrix{Int64}, :, 3) with eltype Int64:
   3
   7

Which would be used something like:

julia> a = rand(10,10,10,10);

julia> selectedaxis = 5
5

julia> indices = 1:2
1:2

julia> selectdim(a,selectedaxis,indices)

Notice that in the documentation example, i is an integer, but you can use ranges of the form i:j as well.

aramirezreyes
  • 1,345
  • 7
  • 16
0

idx = ntuple( l -> l==d ? (i:j) : (:), D)
Y = X[idx...]

Sakurai.JJ
  • 553
  • 3
  • 10