Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# 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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading