A tuple is often used to encapsulate a set of array sizes: sz = size(multi_dim_arr)
and use sz
later. In a similar manner, I sometimes want to encapsulate an array “slice” in an object, but I’m wondering what’s the best way.
arr = rand(Float64, 3, 5)
s = size(arr) # -> Tuple (3,5)
b = fill("hello", s) # works
b = fill("hello", 3, 5) # works, too.
slice = ( :, 2)
c = view(arr, slice) # error
c = view(arr, slice...) # works
d = arr[slice...] # works, too.
slice2 = CartesianIndices((:, 2)) # error
slice2 = CartesianIndices((1:3, 2)) # fine
e = arr[slice2] # works
As you can see, there isn’t quite a “slice object” that can express a general slice. CartesianIndices
comes close but it can’t include a Colon
-only range.
It would be nice if view
and [ ]
accepted a slice object that can be used like
function func(sl2d)
# build a 4D array
t = view(arr4d, sl2d)
u = arr[sl2d]
func_on_2d_arr(t) # or u
end
sl = Slice(4, :, 3, 2:9)
func(sl)
So, my question is whether there is an idiomatic way to encapsulate a slice in a variable (object) and use it later. Is v[tuple...]
the way to go? Or would it make sense to extend view
and [ ]
to take a slice object (as represented by a tuple, for example)?