Dynamic indexing

Given a multi dimensional array A with N dimensions, I want to programmatically index so that : is used for all dimensions but for the k’th dimension it is fixed to a specific value v. Eg for N=4 and k=2 and v=1;


I want to do this selection programmatically. Is it possible?

1 Like

Sure! There’s probably a few different ways of doing this, but here’s one method you could use:

function slicedim(A, k, v)
    prev_indices = ((:) for _ = 1:k-1)
    next_indices = ((:) for _ = k+1:ndims(A))
    getindex(A, prev_indices..., v, next_indices...)


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

julia> # Get the elements of A whose index == 1 in the 3rd dimension

julia> slicedim(A, 3, 1) == A[:,:,1,:]
1 Like

there is also selectdim(A,3,1)