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?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With