Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Views/Operations on Array with flexible number of dimensions

Tags:

julia

Is there an elegant and short way to write the functions that are written below in one go, in a single definition? So that the function operates on an array with flexible number of dimensions, adding the :s as needed? Ideally, so that it also with N dimensions.

ind = 1:5

view_something(A::AbstractArray{T,1}, ind) where {T} = view(A, ind)
view_something(A::AbstractArray{T,2}, ind) where {T} = view(A, :, ind)
view_something(A::AbstractArray{T,3}, ind) where {T} = view(A, :, :, ind)

view_something(rand(10,10,10), ind)
view_something(rand(10,10), ind)
view_something(rand(10), ind)

I noticed that one can call the Colon operator and assemble func args in a vector like that [Colon(),Colon(),...], is this the way to go or are there other ways that are preferred?

like image 920
max xilian Avatar asked Dec 31 '22 11:12

max xilian


2 Answers

eachslice(A, dims = d) gives you an iterator where all other dimensions are :

selectdim(A, d, ind) gives you the individual index.

From the help prompt: ?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.

  See also: eachslice.

and ?eachslice:

  eachslice(A::AbstractArray; dims)

  Create a generator that iterates over dimensions dims of A, returning views that select all the data from the other
  dimensions in A.

  Only a single dimension in dims is currently supported. Equivalent to (view(A,:,:,...,i,:,: ...)) for i in axes(A,
  dims)), where i is in position dims.
like image 175
Nick Bauer Avatar answered Jan 02 '23 01:01

Nick Bauer


How about the following:

ind = 1:5
view_something(A::AbstractArray{T,N}, ind) where {T, N} = 
      view(A, [Colon() for i in 1:(N-1)]..., ind)

view_something(rand(10,10,10), ind)
view_something(rand(10,10), ind)
view_something(rand(10), ind)
like image 27
esel Avatar answered Jan 02 '23 00:01

esel