Indexing array based on a vector including Colon()

question

#1

I’m trying to index a multidimensional array based on a vector using Colon() as well. Is there an easy way to reformulate the getindex function call to allow for varying dimensions of A and corresponding lengths of the indexing vector?

    A=reshape(collect(1:12),(3,2,2))
    index=[:,1,2]
    val=getindex(A,index[1],index[2],index[3])

#2

https://docs.julialang.org/en/v1.0/base/base/#
https://docs.julialang.org/en/v1.0/manual/functions/#Varargs-Functions-1


#3

Thanks for your reply. I fear I didn’t express my aim well enough or didn’t understand the solution you pointed to yet:
I’m trying to pass each field of index to the getindex-function as an argument without writing it out like I do it rn:

    if length(index_set)==3
        result=getindex(variable.innerArray,index_num[1],index_num[2],index_num[3])
    elseif length(index_set)==5
        result=getindex(variable.innerArray,index_num[1],index_num[2],index_num[3]index_num[4],index_num[5])
    end

I understood the solution you provided as an option to write the getindex()-function on a way to accept a varying amount of arguments, correct?


#4

You can always just splat the index set into indexing syntax:

julia> A[index...]
3-element Array{Int64,1}:
 7
 8
 9

But if this is in a hot loop, you’ll soon realize that this isn’t as fast as it could be since splatting the contents of an array isn’t type-stable: Julia’s inference doesn’t know ahead of time how many elements an array might contain or what types they might be (in this case). Better if you can construct your index set as a Tuple instead: index = (:, 1, 2).

There are lots of great tricks Julia has up its sleeve in constructing fast, tight, and readable indexing loops — check out Tim’s posts on multidimensional iteration and the manual for CartesianIndices.