# Indexing array based on a vector including Colon()

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,index,index)
``````
1 Like

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,index_num,index_num)
elseif length(index_set)==5
result=getindex(variable.innerArray,index_num,index_num,index_numindex_num,index_num)
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?

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.

2 Likes