Indexing an array with an array of indices

I have a multidimensional array

A = [ 0 for x=1:5,y=1:5,z=1:5]

I also have an array of indices

I = [1,2,3]

I wish to get the element of A at the indices determined by I. For example I want to retrieve

A[1,2,3]

How do I do this? Just doing

A[I]

gives the wrong answer, because the indices in I are interpreted as linear indices (I guess).

Hi and welcome to the forum!

Try CartesianIndex:

julia> A = [ rand(1:100) for x=1:3,y=1:3,z=1:3]
3Ɨ3Ɨ3 Array{Int64, 3}:
[:, :, 1] =
 26  69  100
 17  28    3
 87  34   10

[:, :, 2] =
 87  85  63
 16  30  59
 59  28  89

[:, :, 3] =
 17  60  34
 56   5  69
 15  44  10

julia> I = (1,2,3)
(1, 2, 3)

julia> A[CartesianIndex(I)]
60

And if your indices are given as a vector, like I=[1,2,3], then use CartesianIndex(I...).

It works. What does ā€¦ mean?

help?> ...
search: ... ..

  ...


  The "splat" operator, ..., represents a sequence of arguments. ... can be used in function
  definitions, to indicate that the function accepts an arbitrary number of arguments. ...
  can also be used to apply a function to a sequence of arguments.

  Examples
  ā‰”ā‰”ā‰”ā‰”ā‰”ā‰”ā‰”ā‰”ā‰”ā‰”

  julia> add(xs...) = reduce(+, xs)
  add (generic function with 1 method)
  
  julia> add(1, 2, 3, 4, 5)
  15
  
  julia> add([1, 2, 3]...)
  6
  
  julia> add(7, 1:100..., 1000:1100...)
  111107

1 Like

If you want A [1,2,3] you have to write A[1,2,3].

julia> A=rand(1:10, (4,3,3))
4Ɨ3Ɨ3 Array{Int64, 3}:
[:, :, 1] =
  5   8  3
  6  10  6
  4   7  5
 10   8  3

[:, :, 2] =
  4  9  3
  4  1  1
 10  6  7
  2  8  5

[:, :, 3] =
 10  4  10
  3  8   9
  8  4  10
  3  5   8

julia> A[1, 2 ,3]
4

If you have I=[1,2,3], one way to write it is A[Iā€¦],

You already know how the ā€¦ works

1 Like

A[I] calls getindex(A, I) under the hood. There are two methods of getindex that will give you the result you want.

  1. getindex(A::Array, I::CartesianIndex)
  2. getindex(A::Array, i1::Integer, i2::Integer, i3::Integer)
julia> A = collect(reshape(1:5*4*3, (5,4,3)))
5Ɨ4Ɨ3 Array{Int64, 3}:
[:, :, 1] =
 1   6  11  16
 2   7  12  17
 3   8  13  18
 4   9  14  19
 5  10  15  20

[:, :, 2] =
 21  26  31  36
 22  27  32  37
 23  28  33  38
 24  29  34  39
 25  30  35  40

[:, :, 3] =
 41  46  51  56
 42  47  52  57
 43  48  53  58
 44  49  54  59
 45  50  55  60

julia> I = CartesianIndex(1,2,3)
CartesianIndex(1, 2, 3)

julia> A[I]
46

julia> A[1,2,3]
46

The answers above are showing you how to convert your I::Vector into one of the other forms by splatting ... it into either the CartesianIndex constructor or directly into the getindex function call.

Relevant Documentation

1 Like