arrofarr = [randn(2,4) for _ in 1:10]
arrofarr[7:end][1:2,3:end] # would select a [4] x [2,2] dim array.
Is this possible? It would be really clean and it could simplify some operation at many place. Also it sounds very intuitive (but of course inbound checks are necessary)
For me I use a function like this:
access_elems(arrs, i) = collect(map(x->x[i], arrs)) # collect is only for timing
access_elems(arrofarr[7:end], [1:2,3:size(arrofarr[1],2)])
which isn’t so nice.
Does anyone know if there is a chance this could be improved later?
You could also broadcast a getindex call, although it’s not as pretty as a comprehension:
getindex.(arrofarr[7:end], Ref(1:2), Ref(3:4))
VectorOfArray from RecursiveArrayTools may be useful, although it’ll return a 3D array with the vector dimension last rather than a vector of 2D arrays:
If you want to use this kind of indexing, presumably the inner arrays are all of the same size, and you probably should represent this data as a multi-dimensional array rather than vector-of-arrays to begin with:
For me I can’t really switch to 3D in spite of the facts that I have the same dims. I have batch of 2D matrices in my case and I have to extend it a lot of time.
Thank you for showing the way, how to do the getindex broadcast version.
So don’t we want to have some support on this array[range1][range2, range3...] It is just beautiful and something that so intuitive, everyone start the syntax with that.
I don’t want to take the emphasis from this topic but are the any plan to support syntactic like:
array[3:] # instead of array[3:end]
array[3:-2] # instead of array[3:end-2]
VectorOfArray isn’t actually stored as a contiguous 3D array in memory, it just has a specialized getindex method that lets you treat it like a 3D array. You can still append to it like arrofarr with push!(arrarr.u, rand(2, 4)). ElasticArrays.jl serves a similar purpose in that it allows you to append to the last dimension of an N-dimensional array, but it’s stored contiguously in memory, so you can’t insert/delete elements in the middle like you can with a VectorOfArray.
The array[range1][range2, range3] syntax is unworkable because of Julia’s order of operations: array[range1] is processed first, and that returns a sub-array of the same shape as the original array (in this case, a Vector):
You can’t index into a vector as if it’s a 2D array for obvious reasons; you need to broadcast the getindex call for each matrix element of the vector.
julia> tmp[2, 4]
ERROR: BoundsError: attempt to access 2-element Vector{Matrix{Float64}} at index [2, 4]
julia> tmp[1][2, 4]
0.9387068354558264
julia> getindex.(tmp, 2, 4)
2-element Vector{Float64}:
0.9387068354558264
-0.735344944870217
There’s a longstanding active proposal to allow index broadcasting with arrofarr[7:end].[1:2, 3:end], and while everybody agrees that it’s nice syntax, there are some corner cases that’ve prevented a decision from being made.