Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index array with Tuple of Tuples

Tags:

indexing

julia

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.

like image 483
flee Avatar asked Sep 17 '25 13:09

flee


2 Answers

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)
like image 143
Przemyslaw Szufel Avatar answered Sep 19 '25 04:09

Przemyslaw Szufel


If in your original question you had a vector of tuples (you have a tuple of tuples) like this:

julia> tupl1 = [(1,1), (2,3), (1,2), (3,1)]
4-element Vector{Tuple{Int64, Int64}}:
 (1, 1)
 (2, 3)
 (1, 2)
 (3, 1)

then you can do just:

julia> m1[CartesianIndex.(tupl1)]
4-element Vector{Int64}:
 1
 0
 1
 1
like image 27
Bogumił Kamiński Avatar answered Sep 19 '25 05:09

Bogumił Kamiński