Index array with vector of tuples

I have a vector of tuples, where each tuple represents a position in a 2d array.

I also have a 2d array of values

For example:

# create a vector of tuples
tupl1 = ((1,1), (2,3), (1,2), (3,1))

# create a 2d array of values
m1 = zeros(Int, (3,3))
m1[1:4] .= 1

I want to get all the values in the 2d array at each of the tuple positions. I thought the following might work:

m1[tupl1]

But this gives in invalid index error. Expected output would be:

4-element Vector{Int64}:
1
0
1
1

Any advice would be much appreciated.

>Solution :

One way to do this could be:

julia> [m1[t...] for t in tupl1]
4-element Vector{Int64}:
 1
 0
 1
 1

More verbose but faster with lesser number of allocations would be via CartesianIndex:

julia> getindex.(Ref(m1), CartesianIndex.(tupl1))
(1, 0, 1, 1)

A benchmark:


julia> @btime [$m1[t...] for t in $tupl1];
  24.900 ns (1 allocation: 96 bytes)

julia> @btime getindex.(Ref($m1), CartesianIndex.($tupl1));
  9.319 ns (1 allocation: 16 bytes)

Leave a Reply