Array of arrays indexing problem

Hello,
If i define an array of arrays like this:

a = [ zeros(10) for i in 1:3 ]

I get an array of 3 elements that are arrays of 10 elements each. Then If I call

a[2][:]

I get an array of length 10 which is normal and fine. But If I call

a[:][1]

I also get an array of length 10 when I expect to have an array of length 3 composed of the first element of each arrays stored in a.
In fact using “:” in one way (a[n][:]) or another (a[:][n]) always gives me back the same array.

Is this an expected behavior and I missed something or simply a bug ?

Here, a[:] is just a syntax to copy a. So a[:][1] gets the first element of a, which has 10 elements.

You want getindex.(a, 1) which applies the function t -> getindex(t, 1) to every element of a.

6 Likes

Ok, a[:] is not simply an indexing operation. Thanks.

It behaves the same as other indexing. a[:] is the same as a[[1, 2, 3]] in that it makes a copy of the elements. See below

julia> t = [6, 7, 8, 9];

julia> s = t[[1, 2, 3]]
3-element Array{Int64,1}:
 6
 7
 8

julia> s[1] = 1000
1000

julia> t
4-element Array{Int64,1}:
 6
 7
 8
 9
2 Likes

I think you are confusing a Vector of Vectors with a matrix (i.e., Array{T, 2}). You can do:

julia> a = [1 2 3; 4 5 6; 7 8 9]
3×3 Array{Int64,2}:
 1  2  3
 4  5  6
 7  8  9

julia> a[:, 1]
3-element Array{Int64,1}:
 1
 4
 7

Note this is a single indexation passing : and 1 separated by a ,, not two indexations executed one after the other. If you have a Vector of Vectors then the outer vector does not know about the inner ones (nor there is guarantee the inner vectors have the same size), so the solution by @pdeffebach is the way to go.

2 Likes

Well there is an allocation/copy with a[:], but I don’t think that’s your issue here. With a[:], you are accessing all the elements of a. You will get the same result with view(a,:)[1] where view(a,:) is “just indexing”.

1 Like